From 02686259b5fdfb0450df7220f417f90da3ede02a Mon Sep 17 00:00:00 2001 From: Brian Han Date: Tue, 10 Oct 2017 12:02:44 -0500 Subject: [PATCH] docs/update-jsx-in-depth/spread-attrs re-add Transferring with ... in JSX docs previously published with React v15-ish --- content/docs/jsx-in-depth.md | 38 +++++++++++++++++++++++++++--------- 1 file changed, 29 insertions(+), 9 deletions(-) diff --git a/content/docs/jsx-in-depth.md b/content/docs/jsx-in-depth.md index 7acc3289..fb2c74b2 100644 --- a/content/docs/jsx-in-depth.md +++ b/content/docs/jsx-in-depth.md @@ -232,20 +232,40 @@ In general, we don't recommend using this because it can be confused with the [E ### Spread Attributes -If you already have `props` as an object, and you want to pass it in JSX, you can use `...` as a "spread" operator to pass the whole props object. These two components are equivalent: +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. + +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`. ```js{7} -function App1() { - return ; -} +const { type, children, ...other } = props; +``` -function App2() { - const props = {firstName: 'Ben', lastName: 'Hector'}; - return ; -} +This ensures that you pass down all the props *except* the ones you're consuming yourself. + +```js{7} +const handleClick = () => console.log("handleClick"); + +const PrimaryButton = props => { + const { type, children, ...other } = props; + return ( + + ); +}; + +const App = () => { + return ( +
+ + Hello World! + +
+ ); +}; ``` -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. +In the example above, the `...other` object contains `{ onClick: handleClick() }` but not the `type` or `children` props. 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. ## Children in JSX