user3486427
user3486427

Reputation: 474

How can I conditionally set default route in react-router-dom v6

I have two pages Page1 and Page2. I need to conditionally set either/or as the homepage based on a condition. I also need to ensure all urls are prefixed with an id. Take the following

<Routes>
  <Route path={`/${id}`} element={condition ? <Page1 /> : <Page2>} />
  <Route path={`/:id/page1`} element={<Page1 />} />
  <Route path={`/:id/page2`} element={<Page2 />} />
  <Route
    path="/"
    element={id 
      ? <Navigate replace to={`/${id}`} />
      : <Navigate replace to={`/`} />} />
    }
  />
</Routes>

This sets the homepage url to '/123' and redirects to '/123' if the user enters '/'. I also have a condition on the first route which dynamically sets the component to render.

My issue is if 'condition' returns a promise then Page2 get set first and when condition is resolved swaps to Page1. Is there a better way to do this?

Upvotes: 1

Views: 993

Answers (2)

tabish munir
tabish munir

Reputation: 61

you need to create two different routes with different path and from home page you write the condition on which page redirect

Home Page

<Link to={true ? '/page1' : '/page2' }/>

Routes

<Route path="/page1" element={<Page1 />} />
<Route path="/page2" element={<Page2 />} />

Upvotes: 0

Drew Reese
Drew Reese

Reputation: 202605

You can create a layout route component that renders on "/:id" and conditionally renders a loading indicator or similar while the condition is verified. When the condition prop is initially undefined the HomePageLayout renders a loading indicator, and when the Promise resolves and updates the condition state to anything other than undefined, an Outlet is rendered for the nested routes.

Example:

const HomePageLayout = ({ condition }) => {
  if (condition === undefined) {
    return <LoadingSpinner />;
  }

  return condition ? <Outlet /> : 
};

Use an index route for rendering either the Page1 or Page2 components. The index route renders exactly when the path equals that of its parent route.

const [condition, setCondition] = useState(); // <-- initially undefined

useEffect(() => {
  getCondition()
    .then(result => setCondition(!!result));
}, []);

...

<Routes>
  <Route path="/:id" element={<HomePageLayout {...{ condition }} />}>
    <Route index element={condition ? <Page1 /> : <Page2>} />
    <Route path="page1" element={<Page1 />} />
    <Route path="page2" element={<Page2 />} />
  </Route>
  <Route
    path="/"
    element={<Navigate replace to={id ? `/${id}` : "/"} />}
  />
</Routes>

Upvotes: 1

Related Questions