1- I want to wrap "Model" component with "ModelStateProvider" like below but it does not work. I searched Google and couldn't find any practical solution. I would like to know if there is a way to make it work.
2- I wonder if it would be practical and efficient to wrap the whole app with "ModelStateProvider" like "AuthStateProvider" but keep that in mind I will be consuming "ModelStateProvider" only with "Model" component.
Can you help me to get some idea please?
Thank you :]
const App = () => {
return (
<AuthStateProvider>
<Router>
<Navbar />
<main className='container'>
<Route exact path='/' component={Homepage} />
<Switch>
<Route exact path='/signin' component={Signin} />
<Route exact path='/signup' component={Signup} />
<ModelStateProvider>
<Route exact path='/model/:link' component={Model} />
</ModelStateProvider>
<Route exact path='/models' component={Models} />
<Route exact path='/profiles' component={Profiles} />
<PrivateRoute exact path='/account' component={Account} />
<PrivateRoute exact path='/publish' component={Publish} />
</Switch>
</main>
</Router>
</AuthStateProvider>
)
}
EDIT: Rendering it inside of the Route fixed it. Since I needed the path, I passed it as props. You can see the solution below.
<Route
exact
path='/model/:link'
render={(path) => (
<ModelStateProvider>
<Model path={path} />
</ModelStateProvider>
)}
/>
Instead of passing a component prop to the route, you could use the implicit children prop, which is what the documentation for Switch shows in the example.
<Switch>
<Route … />
<Route exact path='/model/:link'>
<ModelStateProvider>
<Model />
</ModelStateProvider>
</Route>
…
</Switch>
If that doesn't satisfy your constraints for routing or route matching, or if you can't pass all router props to the immediate children of the provider for some reason, you could make a composite component that wraps the provider and model:
const ModelWithProvider = (props) => (
<ModelStateProvider>
<Model {...props} />
</ModelStateProvider>
);
// …
<Switch>
<Route … />
<Route exact path='/model/:link' component={ModelWithProvider} />
…
</Switch>
And if that doesn't work or isn't possible to wrap ahead of time for some reason, you could just wrap the Switch (or Router, or whatever ancestor you want) with ModelStateProvider. You alluded to this in your question but you didn't explain why or how that doesn't work for you other than "efficiency." Is there anything flagrantly inefficient about your app when you tried that?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With