Search code examples
reactjsinheritancenestedcomponents

Understanding component prop inheritence in React


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:

  1. What is the relationship between this parent and child in this example?

  2. Does the child have access to all the same parent properties as it would in Example A?

  3. Does the parent construct look any different as to how it acknowledges something that can be nested inside it?

  4. What are the proper terms for this two different ways of doing things?


Solution

  • I think that this page will help you.

    1. What is passed inside the "parent" component will be available under props.children. So the child component is a props of the parent component.
    2. No but the child component is probably being used somewhere in the parent component to be displayed and the parent component can give additional props to the child to use its properties. Here is an exemple.

    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>

    1. Yes it uses props.children

    const parent = (props) => { return <div>Here is my child: {props.children}</div> }

    1. I guess this is the name of the link if I'm not mistaking.