HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptreactCritical

What is {this.props.children} and when you should use it?

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
whatpropswhenuseyouandshouldchildrenthis

Problem

Being a beginner to React world, I want to understand in depth what happens when I use {this.props.children} and what are the situations to use the same. What is the relevance of it in below code snippet?

render() {
  if (this.props.appLoaded) {
    return (
      
        
        {this.props.children}
      
    );
  }
}

Solution

What even is ‘children’?

The React docs say that you can use props.children on components that represent ‘generic boxes’ and that don’t know their children ahead of time. For me, that didn’t really clear things up. I’m sure for some, that definition makes perfect sense but it didn’t for me.

My simple explanation of what this.props.children does is that it is used to display whatever you include between the opening and closing tags when invoking a component.

A simple example:

Here’s an example of a stateless function that is used to create a component. Again, since this is a function, there is no this keyword so just use props.children

const Picture = (props) => {
  return (
    
      
      {props.children}
    
  )
}


This component contains an ` that is receiving some props and then it is displaying {props.children}.

Whenever this component is invoked,
{props.children} will also be displayed and this is just a reference to what is between the opening and closing tags of the component.

//App.js
render () {
  return (
    
      
          //what is placed here is passed as props.children  
      
    
  )
}


Instead of invoking the component with a self-closing tag
if you invoke it with full opening and closing tags you can then place more code between it.

This de-couples the
` component from its content and makes it more reusable.

Reference: A quick intro to React’s props.children

Code Snippets

const Picture = (props) => {
  return (
    <div>
      <img src={props.src}/>
      {props.children}
    </div>
  )
}
//App.js
render () {
  return (
    <div className='container'>
      <Picture key={picture.id} src={picture.src}>
          //what is placed here is passed as props.children  
      </Picture>
    </div>
  )
}

Context

Stack Overflow Q#49706823, score: 348

Revisions (0)

No revisions yet.