Reputation: 11
Looking at the react-redux docs, I'm confused on how the object spread notation transforms an object to become props. On the example below:
const TodoList = ({ todos, onTodoClick }) => (
<ul>
{todos.map(todo =>
<Todo
key={todo.id}
{...todo}
onClick={() => onTodoClick(todo.id)}
/>
)}
</ul>
)
how does the {...todo}
get transformed to work inside-
const Todo = ({ onClick, completed, text }) => (
<li
onClick={onClick}
style={{
textDecoration: completed ? 'line-through' : 'none'
}}
>
{text}
</li>
)
I know the {...todo}
returns an object that has keys completed, text, and id. But how does that get extracted out to fit into the const Todo
function? Are the arguments that get passed into this function always going to correspond exactly to the props that get passed in from TodoList?
Upvotes: 1
Views: 133
Reputation: 5742
Exactly, consider:
const MyParentComponent = () => {
const bar = { a: 'Hello', b: 'world' }
return <MyChildComponent foo={ '!' } {...bar} />
}
const MyChildComponent = ({ a, b, foo }) => (
<div>{ `${a} ${b}${foo}` }</div>
)
Thanks to the spread notation, bar
's keys (a
and b
) are extracted and passed as props to the child component.
Which is different from rest parameters:
const MyParentComponent = () => (
<MyChildComponent a={ 'Hello' } b={ 'world' } foo={ '!' } />
)
const MyChildComponent = ({ a, b, ...bar }) => ({
<div>{ `${a} ${b}${bar.foo}` }</div>
})
Notice that in this case bar
is an object containing all the extra keys that are not destructured.
Upvotes: 2