Home > database >  Is there a way to match routes in react-router-dom v6 based on whether the route exists in an object
Is there a way to match routes in react-router-dom v6 based on whether the route exists in an object

Time:09-05

I recently migrated to react-router-dom v6, and there is one item I need to change which I am a bit confused with. Basically, I have routes at /projects/:id and I want to direct to <Project /> if id exists in an object called projects, and to otherwise direct to <NotFound />.

I have this object:

const projects = {
    sample: {
        // properties
    },
    sample2: {
        // properties
    },
    sample3: {
        // properties
    }
}

But I am unsure how to check if the id in route matches any of the items in projects above, so I have the following, broken code:

<Routes>
  <Route path="/" element={ <Home /> } />
  <Route path="/about" element={ <About /> } />
  <Route path="/projects/:id" element={ ({ match }) => (
    match ? <Project /> : <NotFound /> 
  )} />
  <Route path="*" element={ <NotFound /> } />
</Routes>

Ideally, /projects/sample2 should be a valid route, rendering <Project />, but /projects/sample5 should not be a valid route, and therefore it should direct to <NotFound />.

But I'm not sure what prop should be used and matched, and how to do it :(

CodePudding user response:

You can use params.id in projects in your Route or inside the Project component:

params.id in projects ? /* render project */ : <NotFound />

CodePudding user response:

const isProject = !!Object.entries(projects).filter(sample=>sample[1].id ===id);

// provided that id is one of the keys in properties; 

element={isProject ? <Project /> : <NotFound /> }

CodePudding user response:

You can try to changing in the following way:

<Routes>
  <Route path="/" element={ <Home /> } />
  <Route path="/about" element={ <About /> } />
  <Route path="/projects/:id" element={ <Project /> } />
  <Route path="/404" element={ <NotFound /> } />
  <Route path="*" element={<Navigate to="/404" replace />} />
</Routes>

In the Project component, you can use useEffect to redirect to NotFound page

const { id } = useParams();
const navigate = useNavigate();

...

useEffect(() => {
  if (/* ex: response.status == 404 || !id || ... */) {
    navigate("/notfound", { replace: true });
  }
}, [id, navigate]);
  • Related