Thursday, 1 June 2023

How is props.children added inside opening and closing tags in React JS with children="xyz" attribute?

This is how I understand props.children in React:

class ThemedButton extends React.Component {
  render() {
    console.log(this.props);
    return ( <
      button > {
        this.props.children
      }
      " 12345" <
      /button>
    );
  }
}

function Toolbar(props) {
  return ( <
    ThemedButton onClick = {
      props.changeTheme
    } >
    Change Theme <
    /ThemedButton>
  );
}



ReactDOM.render( < Toolbar / > , document.getElementById('root'));
//this will generate <button>Change Theme 12345</button>
<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>

So basically any child node(s) of ThemedButton will be put in place of props.children. This makes sense, but what doesn't make sense is if I omit props.children and instead just pass {...props} as attribute or use children attribute as property on the button tag, it still inserts the child node(s). Following is the example:

class ThemedButton extends React.Component {
  render() {
    console.log(this.props);
    return ( 
    <button {...this.props}  ></button>  //child nodes are added automatically     
    );
  }
}

class ThemedButton2 extends React.Component {
  render() {
    console.log(this.props);
    return ( 
    <button children="XYZ"  ></button>
    );
  }
}


function Toolbar(props) {
  return ( 
  <React.Fragment>
    <
    ThemedButton onClick = {
      props.changeTheme
    } >
    Change Theme <
    /ThemedButton>
    <ThemedButton2> Change theme2 </ThemedButton2>
  </React.Fragment>
  );
}



ReactDOM.render( < Toolbar / > , document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.1/umd/react-dom.production.min.js"></script>

<div id="root"></div>

As you can see {...props} on button seemingly brings actual child nodes of ThemedButton> as children property. In ThemedButton2 I manually provided children="xyz", which automatically inserts xyz as child nodes of button.

Why is this happening? Where does react explain this in it's official documentation?



from How is props.children added inside opening and closing tags in React JS with children="xyz" attribute?

No comments:

Post a Comment