Single <Provider> for many components

I have the following structure in my root component

<div className={styles.main_container}>
  <Provider store={store}>
    <Topbar></Topbar>
  </Provider>
  <div className={styles.scene_and_tools}>
    <Provider store={store}>
      <Sidebar></Sidebar>
    </Provider>
    <Provider store={store}>
      <Scene></Scene>
    </Provider>
  </div>
  <Provider store={store}>
    <Timeline></Timeline>
  </Provider>
</div>

This works fine but I find it a bit not so "DRY" to repeat <Provider> for every single component that I want to pass context. So I tried

<div className={styles.main_container}>
  <Provider store={store}>
    <Topbar></Topbar>
  <div className={styles.scene_and_tools}>
      <Sidebar></Sidebar>
      <Scene></Scene>
  </div>
    <Timeline></Timeline>
  </Provider>
</div>

But I am getting the following error:

Failed propType: Invalid prop `children` supplied to `Provider`,
expected a single ReactElement. Check the render method of `App`.

Is there a way to make my code more DRY or I have to live with this redundancy?

Answers


The first variation is completely redundant. The only reason Provider exists in the first place is so that you can avoid passing the store down and explicitly. Otherwise you could just as well remove it and pass store as a prop to container components themselves.

The intended use case for Provider is to wrap the rootmost component. All children and grandchildren will then receive the store implicitly. You should only do it once, and put a single React element inside. Your second example does not work because you put three elements inside it: Topbar, div and Timeline. Wrap the outer div instead and it will work. Better yet, move Provider to the place where you call ReactDOM.render() and wrap your rootmost App component in it. Then you don't need it anywhere else.


Need Your Help

Having a hard time on figuring out how to move my snake constantly

java std jgrasp

So I'm creating a java game called snake, I'm currently stuck on how to get the start of the snake to constantly moved after it is initially moved, Im trying to use the thread.sleep but I'm pretty ...

Swift: Pause endless scrolling background (i.e. infinite loop)

swift loops sprite-kit sprite pause

In my game I would like certain things to pause when the "endGame" function is called, while other things stay running. I have been able to accomplish this for most actions by using the "paused" bo...