Reputation: 475
const AppRendrer =(props)=>(<div {...props}/>)
class App extends React.Component{
render(){
return <AppRendrer>This is test</AppRendrer>
}
}
export default App;
Output of above is "This is test" if i use <div {...props}/>
const AppRendrer =(props)=>(<div>{props.children}</div>)
class App extends React.Component{
render(){
return <AppRendrer>This is test</AppRendrer>
}
}
export default App;
Output of above is also "This is test" if i use {props.children}
can any on explain how <div {...props}/> and <div>{props.children}</div>
are same
thanks in advance.
Upvotes: 2
Views: 689
Reputation: 222503
JSX is syntactic sugar for React.createElement
, children of React element are translated to children
prop due to the way how createElement
works.
<p className="class">foo</p>
is transformed to
React.createElement('p', { className: 'class' }, 'foo');
It's the same thing as:
React.createElement('p', { className: 'class', children: 'foo' });
Both result in React element object:
{ type: 'p', props: { className: 'class', children: 'foo' }, ... }
createElement
supports children as separate arguments in order to make it more concise when it's used without JSX:
React.createElement('p', null,
React.createElement('b', null,
'foo'
)
);
<div {...props}/>
and <div>{props.children}</div>
are not the same. <div {...props}/>
passes all props while <div>{props.children}</div>
passes only children
. They work the same way only because there were no other props.
They would be the same if they were <div children={props.children}/>
and <div>{props.children}</div>
.
Upvotes: 3
Reputation: 35797
In React, nesting components like this:
<ComponentA>
<ComponentB />
</ComponentA>
...is treated the same as if you'd passed a prop called children
:
<ComponentA children={<ComponentB />} />
In your first example, you're passing all of the props from AppRendrer
down to the div
element (via the prop spread syntax) - this includes the children
, if present.
Upvotes: 1