Skip to content

Commit

Permalink
add docs for shadow dom options
Browse files Browse the repository at this point in the history
  • Loading branch information
janbiasi committed Oct 15, 2023
1 parent d0a8f88 commit ac02aac
Showing 1 changed file with 38 additions and 14 deletions.
52 changes: 38 additions & 14 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,12 @@ Previous versions (< 3.0.0) implemented the v0 proposal, which was only implemen

## Usage

Import `register` and call it with your component, a tag name<strong>*</strong>, and a list of attribute names you want to observe:
Import `register` and call it with your component, a tag name<strong>\*</strong>, and a list of attribute names you want to observe:

```javascript
import register from 'preact-custom-element';

const Greeting = ({ name = 'World' }) => (
<p>Hello, {name}!</p>
);
const Greeting = ({ name = 'World' }) => <p>Hello, {name}!</p>;

register(Greeting, 'x-greeting', ['name']);
```
Expand Down Expand Up @@ -42,15 +40,15 @@ import register from 'preact-custom-element';

// <x-greeting name="Bo"></x-greeting>
class Greeting extends Component {
// Register as <x-greeting>:
static tagName = 'x-greeting';
// Register as <x-greeting>:
static tagName = 'x-greeting';

// Track these attributes:
static observedAttributes = ['name'];
// Track these attributes:
static observedAttributes = ['name'];

render({ name }) {
return <p>Hello, {name}!</p>;
}
render({ name }) {
return <p>Hello, {name}!</p>;
}
}
register(Greeting);
```
Expand All @@ -60,15 +58,41 @@ If no `observedAttributes` are specified, they will be inferred from the keys of
```js
// Other option: use PropTypes:
function FullName(props) {
return <span>{props.first} {props.last}</span>
return (
<span>
{props.first} {props.last}
</span>
);
}
FullName.propTypes = {
first: Object, // you can use PropTypes, or this
last: Object // trick to define untyped props.
first: Object, // you can use PropTypes, or this
last: Object, // trick to define untyped props.
};
register(FullName, 'full-name');
```

### Using the shadow DOM

It is possible to attach a shadow root to the custom element to have your component rendered in a separate subtree.
Customization of the shadow root `mode` is also possible on element basis.
Read more about the shadow DOM on [MDN](https://developer.mozilla.org/en-US/docs/Web/API/ShadowRoot).

```tsx
function WithShadow(props) {
return <span>Hello from shadow root!</span>;
}

// use shadow root in "open" mode
register(FullName, 'full-name', [], {
shadow: true,
});

// use shadow root in "closed" mode
register(FullName, 'full-name-encapsulated', [], {
shadow: true,
mode: 'closed',
});
```

## Related

Expand Down

0 comments on commit ac02aac

Please sign in to comment.