Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How "props.children" works on a React component?

I was working on the code of a practice for React, but I stopped because I have to make a navigation bar be shared among other pages

I found the next solution and it works but I don't know how exactly works; this is for a course project.

function Layout(props) {
  return(
    <React.Fragment>
      <Navbar />
      {props.children}
    </React.Fragment>
  );
}

I can't really know what really {props.children} does and how if Layout component start holding other components the Navbar component still appears

<Layout>
  <Switch>
    <Route exact path="/badges" component={Badges}/>
    <Route exact path="/badges/new" component={BadgeNew} />
  </Switch>
</Layout>

What happens behind the scenes?

like image 726
Pablo Verduzco Avatar asked Oct 19 '25 13:10

Pablo Verduzco


2 Answers

props.children means that React will render whatever u put between Layout component.

For ex, if u put a div block between Layout components, props.children will be that div.

like image 106
TsungJui Wang Avatar answered Oct 21 '25 02:10

TsungJui Wang


Every JSX code that you put inside the Layout-tag, will be placed in children property of props-object of the Layout Component.

<Layout>
  <div>this is a child</div>
  <AnotherReactComponentAsLayoutChild/>
</Layout>
like image 41
wuarmin Avatar answered Oct 21 '25 01:10

wuarmin