Reputation: 1059
I'm posting this because I'm not actually sure how to ask it with the correct terminology without an example. Is there any difference in how properties are inherited with these two different ways of nesting components in React.
Example A
You have a parent component with the property color
that you pass a string into.
<parent color={'blue'}/>
The constructor of the parent has a <child/>
component in it that can receive the prop an use it in as below. I understand how this works.
// in parent constructor
render (
<div>
<child background={this.props.color}/>
</div>
)
Example B
In this case the <child/>
component isn't actually inside the constructor of the <parent/>
component but it inside the element as seen below.
<parent color={'blue'}>
<child background={this.props.color}/>
</parent>
So my question is fourfold:
What is the relationship between this parent and child in this example?
Does the child have access to all the same parent properties as it would in Example A?
Does the parent construct look any different as to how it acknowledges something that can be nested inside it?
What are the proper terms for this two different ways of doing things?
Upvotes: 0
Views: 28
Reputation: 452
I think that this page will help you.
const Parent = (props) => {
//To add props to the children
return React.cloneElement(props.children, { extraProps: "extraProps" })
}
const Child = (props) => {
return <div>
<div>{props.extraProps}</div>
{props.myProps}
</div>
}
const App = (props) => {
return <Parent>
<Child myProps="baseProps "/>
</Parent>
}
ReactDOM.render(
<App />,
document.getElementById('root')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"></div>
const parent = (props) => { return <div>Here is my child: {props.children}</div> }
Upvotes: 1