MarcL
MarcL

Reputation: 3593

React: Which Order to "wrap" components with HOC?

I would be interested in the ways how to wrap components in what order with HOCs (Higher-order components), e.g:

const app = (
    //Provider has to wrap everything
    <someContext.Provider value={{message:"Ringeldingeldong"}}>
        <Provider store={store}>
            <BrowserRouter>
                <App />
            </BrowserRouter>
        </Provider>
    </someContext.Provider>
)

EDIT: as I found out, it doesnt make any difference which component wraps another component, there seems not to be an order how to wrap components with HOC (at least for Router, ContextProvider and Redux store as it seems...)

In this case, browserRouter can have only 1 child, but what If I also want to use some global context Provider for my App component? and if I would like to use a react-redux for all my components in addition?

What is the general order how to use and wrap those components in HOCs, and is this in general possible to wrap components multiple times with other HOCs or not?

Upvotes: 2

Views: 1040

Answers (1)

onuriltan
onuriltan

Reputation: 3908

You can do that by importing Router, Route and Switch from react-router-dom library in your main component and wrap Router with Provider inside JSX, for example

App.js

...
import { BrowserRouter as Router, Route, Switch} from "react-router-dom";
import { Provider } from 'react-redux'
import store from './store'

const App = () => {
  return (
    <Provider store={store}>
      <Router>
        <Switch>
          <Route exact path='/' component={Home} />
          <Route exact path='/about' component={About} />
          <Route exact path='/login' component={Login} />
          <Route exact path='/register' component={Register} />
        </Switch>
      </Router>
    </Provider>    
  );
}

export default App;

This way you can get props from Redux in all of your components that are in Route

Upvotes: 2

Related Questions