How to render different message based on current url / url fragment

317 Views Asked by At

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.

2

There are 2 best solutions below

0
On BEST ANSWER

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> }
  </>);
}
0
On

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:

App

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>
  );

Snackbar

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.