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)
26,545 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)
221,520 students enrolled
44 hours of video content
View Course
Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)
Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)
114,575 students enrolled
21 hours of video content
View Course