Reputation:
Here I am returning the current react dom stuff:
return (
<React.Fragment>
{inProduction ? null : <CP.Dev/>}
<CP.Snackbar
{...p as any}
/>
<Router history={browserHistory}>
<Switch>
<Route path="/login" component={Login} />
<Route path="/signup" component={Signup} />
{authRoutes}
</Switch>
</Router>
</React.Fragment>
);
so..the Snackbar component renders for every route - goal: what I want to do is render a different welcome message depending on what the url is - what is the best way to do this? How can I listen for a url change and then render a different message depending on the url?
Alternatively, I could wrap every component with Snackbar and then hardcode a key to a different message, but that seems unnecessary.
Upvotes: 6
Views: 327
Reputation: 4748
You can use react-router-dom
history
to know about the changes in the URL. Here is an example:
import React from "react";
import { useHistory } from "react-router-dom";
const App = () => {
const history = useHistory();
return (<>
{ history.location.pathname === "/" ? <div>Home</div> : <div>Other Component</div> }
</>);
}
Upvotes: 2
Reputation: 1701
You are passing the browserHistory to the Router. Why don't you pass the same to the Snackbar component? There will be url and location in the history object, These can be made use inside the Snackbar and render the message as you need. For example:
import React from "react";
const App = () => (
<React.Fragment>
{inProduction ? null : <CP.Dev/>}
<Snackbar
{...p as any}
history={browserHistory}
/>
<Router history={browserHistory}>
<Switch>
<Route path="/login" component={Login} />
<Route path="/signup" component={Signup} />
{authRoutes}
</Switch>
</Router>
</React.Fragment>
);
const SnackBar = ({history, ...props}) => {
// const message = `Current location is ${history.location.url}`;
// Format and use the message as needed
return (
<>
<CP.Snackbar
{...props}
/>
</>
);
}
PS: If you want to access the location inside any subcomponent of Router
, I recommend using useLocation
hook. But in this case the Snackbar
is a sibling and react-router context won't be set to use the router hooks.
Upvotes: 2