Search code examples
reactjscarbon-design-system

Render method in React carbon design component


I'm working with Carbon design & React - following the example:

<HeaderContainer render={({
        isSideNavExpanded,
        onClickSideNavExpand
      }) => {
        console.log("Rendering", onClickSideNavExpand)
        console.log("Rendering", isSideNavExpanded)
        return (<> ... 
                   <HeaderMenuButton aria-label={isSideNavExpanded ? 'Close menu' : 'Open menu'} onClick={onClickSideNavExpand} isActive={isSideNavExpanded} aria-expanded={isSideNavExpanded} />
                   my stuff 
                   ...</>)
}/>

I don't understand the render method here. What is the difference between this method and between using "children", something like:

<HeaderContainer>
 <> 
  <HeaderMenuButton aria-label={isSideNavExpanded ? 'Close menu' : 'Open menu'} onClick={onClickSideNavExpand} isActive={isSideNavExpanded} aria-expanded={isSideNavExpanded} />
  ... my stuff ... 
 </>
</HeaderContainer>

Why implement it the first way instead of the second? I think it's much less readable...


Solution

  • passing a render function is called render prop

    The term “render prop” refers to a technique for sharing code between React components using a prop whose value is a function.

    A component with a render prop takes a function that returns a React element and calls it instead of implementing its own render logic.

    if isSideNavExpanded and onClickSideNavExpand exist inside of HeaderContainer, you can't pass them to HeaderMenuButton as in your second example.

    const Component = ({render}) => {
      const localData = ...      // this lies inside the children component
      return render(localData)   // this is how the parent access the data
    }
    
    <Component render={(dataFromComponent) => {  // access data from Component
      ...do something with data
      return view
    }} />