Skip to content

Commit 8ccb0c4

Browse files
authored
Rewrite spread attrs section based on feedback
1 parent 4c5f48c commit 8ccb0c4

File tree

1 file changed

+13
-22
lines changed

1 file changed

+13
-22
lines changed

content/docs/jsx-in-depth.md

Lines changed: 13 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -245,40 +245,31 @@ function App2() {
245245
}
246246
```
247247

248-
Spread attributes can be useful when you are building generic containers. However, they can also make your code messy by making it easy to pass a lot of irrelevant props to components that don't care about them. We recommend that you use this syntax sparingly.
248+
You can also pick specific props that your component will consume while passing all other props using the spread operator.
249+
This ensures that the component consumes the `kind` prop only, and passes down all other props via `...other`.
249250

250-
An alternative to spreading all of your props is to specifically list out all the properties that you would like to consume, followed by `...other`.
251-
252-
```js
253-
const { children, ...other } = props;
254-
```
255-
256-
This ensures that you pass down all the props *except* the ones you're consuming yourself.
257-
258-
```js{6}
259-
const handleClick = () => console.log("handleClick");
260-
261-
const PrimaryButton = props => {
262-
const { children, ...other } = props;
263-
return (
264-
<button {...other}>
265-
{children}
266-
</button>
267-
);
251+
```js{2}
252+
const Button = props => {
253+
const { kind, ...other } = props;
254+
const className = kind === "primary" ? "PrimaryButton" : "SecondaryButton";
255+
return <button className={className} {...other} />;
268256
};
269257
270258
const App = () => {
271259
return (
272260
<div>
273-
<PrimaryButton type="button" onClick={handleClick}>
261+
<Button kind="primary" onClick={() => console.log("clicked!")}>
274262
Hello World!
275-
</PrimaryButton>
263+
</Button>
276264
</div>
277265
);
278266
};
279267
```
280268

281-
In the example above, the `...other` object contains `{ onClick: handleClick(), type: "button" }` but *not* the `children` prop. This makes a component like the `PrimaryButton` more reusable and flexible because it can extract a set of unknown properties like `onClick` in the above example.
269+
In the example above, the `kind` prop is safely consumed and *is not* passed directly to the `<button>` element in the DOM.
270+
All other props are passed via the `...other` object making this component really flexible. You can see that it passes an `onClick` and `children` props.
271+
272+
Spread attributes can be useful but not to pass invalid HTML attributes to the DOM. They can also make your code messy by making it easy to pass a lot of irrelevant props to components that don't care about them. We recommend using this syntax sparingly.
282273

283274
## Children in JSX
284275

0 commit comments

Comments
 (0)