Home > other >  Dynamic views based on url ID with React Router V6
Dynamic views based on url ID with React Router V6

Time:03-15

I'm doing a movie app that displays a list of movies, and when you click on a certain movie, it opens the movie view with more info about it. Currently, I learned how to do it with an older version of React Router and it went like this (I'm also using bootstrap):

<Route path="/movies/:movieId" render={({ match }) => {
  return 
   <Col md={8}>
     <MovieView movie={movies.find(m => m._id === match.params.movieId)} 
   </Col>
}}/>

The MovieView renders the movie depending on the movie requested by the URL as a Bootstrap Card element. I wanted to keep using this same concept, but updating it to React Router V6. I know that they removed Route props like match and so, but I wanted to know if I could still have this dynamic going on with the newer version.

I was able to update the main page which shows all movies on my database, and the code reads as follow with V6:

<Route exact path="/" element={
   movies.map(m => (
      <Col md={3} key={m._id}>
         <MovieCard movie={m} />
      </Col>
    ))
} />

But, as the MovieView requires the URL to match and ID, it doesn't work because I need the match to be defined.

If anyone knows a way to work around this I'd be very glad. Thanks a lot!

CodePudding user response:

You can create a wrapper component to read the movieId route path param via the useParams hook, do the filtering, and pass the movie prop.

Example:

import { useParams } from 'react-router-dom';

...

const MovieWrapper = () => {
  const { movieId } = useParams();

  return (
    <Col md={8}>
      <MovieView movie={movies.find(m => m._id === movieId)} />
    </Col>
  );
};

...

<Route path="/movies/:movieId" element={<MovieWrapper />} />
  • Related