0
votes

So I'm trying to set a path as my landing page and keep the the main application on root.

Eg: Let's say app is myapp.com. When a user hits the URL, I want him to be redirected to myapp.com/welcome which serves as a landing page.

On that page however there is a CTA button which redirects him to the main application, which is the root path, so myapp.com.

So my issue is that if (on the root) I use <Redirect to="/welcome" /> to navigate the user on the landing page, then I'm stuck, I can't reach the main app.

Any ideas how to make it work?

1

1 Answers

0
votes

I haven't used React Router for a while now so I'm a bit rusty, but I managed to find the answer myself.

I dedided to share the question anyway. It might help others.

My solution:

import { useEffect, useState } from 'react';
import { Redirect, Route, Switch, withRouter } from 'react-router-dom';
import LandingContainer from './landing/LandingContainer';
import MainContainer from './MainContainer';

const App = () => {
  const [isFirstLoading, setIsFirstLoading] = useState(true);

  useEffect(() => {
    if (isFirstLoading) {
      setIsFirstLoading(false);
    }
  }, [isFirstLoading]);

  return (
    <Switch>
      <Route path="/welcome" component={LandingContainer} />
      {isFirstLoading && <Redirect to="/welcome" />}
      <Route path="/" component={MainContainer} />
    </Switch>
  );
};

export default withRouter(App);

Keep in mind that this solution doesn't include session handling, so if you refresh the page or remove the /welcome part manually, you will be redirected. With NavLink however it works like a charm.

Any further suggestions or improvements are welcomed!