React Router Dom change URL on website load

Viewed 3382

With React Router Dom, how can I change the URL of the website as soon as the site loads?

I have tried adding the following as an 'onLoadedMetadata' event on the main div for the nav, which loads on start.

 const loadHandler = () => {
    useHistory.push("./home");
  };

I also tried a similar method using 'useHistory.push("/home")' with use effect, and then triggering that when the location function from React Router Dom loads in. I wasn't able to achieve the result I'm looking for though.

I have set up the links and routes correctly, I just can't figure out how to make the URL change as soon as the website loads.

Thanks in advance.

2 Answers

You can redirect useEffect to window.location.href="/example" in your startup file (Probably App.js).

 useEffect(() => {
    window.location.href="/example"
  });

You can use Redirect to redirect user to different routes.

Here render props with Redirect is used.

<BrowserRouter>
<Route
    exact
     path="/"
     render={() => {
        return <Redirect to="/about" />;
     }}
  />
  <Route path="/about" component={About} />
  <Route path="/home" component={Home} />
  <Route path="/topics" component={Topics} />
</BrowserRouter>

Using Just Redirect

<BrowserRouter>

  <Redirect from='/' to='/about' />
  <Route path="/about" component={About} />
  <Route path="/home" component={Home} />
  <Route path="/topics" component={Topics} />
</BrowserRouter>

Simple Code Sandbox Demo

Related