by Sai gowtham

Intro to React props.children

In this tutorial, we are going to learn about how to use props.children in React.

Note: If you don’t know about props then checkout A beginners guide to react props

Props.children

In reactjs props.children is used to add the data between the opening and closing JSX tags.

Let’s see an example:

function Sidebar(props) {

    return (
        <div className="sidebar">
            {props.children}        </div>
    )
}


<Sidebar>
    <nav>        <a href="#">Home</a>        <a href="#">Posts</a>        <a href="#">Contact</a>    </nav></Sidebar>

In Sidebar component we defined props.children inside the div tag, if we pass anything between the Sidebar opening and closing jsx tags that data will be passed to props.children property and renders inside the <div>.

react-props.children

In class based components we need to use this.props.children instead of props.children.

Let’s refactor our code by using classes.

class Sidebar extends React.Component {

    render() {
        return (
            <div className="sidebar">
                {this.props.children}            </div>
        )
    }
}


<Sidebar>
    <nav>        <a href="#">Home</a>        <a href="#">Posts</a>        <a href="#">Contact</a>    </nav></Sidebar>

More examples

function Posts(props){

   return (
       <div className="posts">
         {props.children}
       </div>
   )

}

function Share(props){

    return (
        <div>
          <button>{props.name}</button>
        </div>
    )
}


<Posts>
    <h1>this my heading</h1>
    <p>this is big old post</p>
    <Share name="facebook"/>
    <Share name="twitter"/>
</Posts>

react props.children exmaple

Top Udemy Courses

JavaScript - The Complete Guide 2020 (Beginner + Advanced)
JavaScript - The Complete Guide 2020 (Beginner + Advanced)
45,614 students enrolled
52 hours of video content
View Course
React - The Complete Guide (incl Hooks, React Router, Redux)
React - The Complete Guide (incl Hooks, React Router, Redux)
284,472 students enrolled
40 hours of video content
View Course
Vue - The Complete Guide (w/ Router, Vuex, Composition API)
Vue - The Complete Guide (w/ Router, Vuex, Composition API)
130,921 students enrolled
48.5 hours of video content
View Course