Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Dynamic views based on url ID with React Router V6

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

<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!

>Solution :

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 />} />
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading