2

I have consumer, which receive context from provider:

const ViewModeConsumer = ({children}) => (
  <ModeContext.Consumer>
    {context => (
      <aside>{children}</aside>
    )}
  </ModeContext.Consumer>
)

I want to use context inside children element, and set it as a props to nested elements. What is the correct way to do this?

Thanks in advance.

Vladimir Humeniuk
  • 2,271
  • 2
  • 23
  • 47

1 Answers1

2

You can use React.cloneElement to pass props to children

const ViewModeConsumer = ({children}) => (
  <ModeContext.Consumer>
    {context => (
      <aside>
         {React.Children.map(children, child => {
              return React.cloneElement(child, {context});
         })}
      </aside>
    )}
  </ModeContext.Consumer>
)

However if your parent logic is just to pass context onto its children, Then its probably better to write an HOC for which you call for each component instead of rendering them as children to a parent component

const withViewModeContext = (Component) => {
    return (props) => (
      <ModeContext.Consumer>
        {context => (
             <Component {...props} context ={context} />
        )}
      </ModeContext.Consumer>
     )
}

and access the context within the children from props.

If you are on v16.6.0 or above of React, you don't even need an HOC and can defined static contentTypes for the children component

You can refer this post for more details: Access React Context outside of render function

Shubham Khatri
  • 211,155
  • 45
  • 305
  • 318