react-router-dom v6: What would be the equivalent to Route's render prop?

Viewed 1270

In my App.js file, I was previously able to render a dynamic route using the following approach:

<Route exact path="/episodes/:id" render={(props) => {
    const episodeNumber = props.location.pathname.replace('/episodes/', '');
    return (
        <EpisodeDetails episode={this.state.episodes[episodeNumber]} />
    );
}}/>

EpisodeDetails.js

const EpisodeDetails = (props) => {
    return (
        <div className="Episode">
            <h2><span>Episode {props.episode.id}: </span>{props.episode.title}</h2>
            <p>{props.episode.description}</p>
            <audio controls>
                <source src={props.episode.source} type="audio/mp3" />
            </audio>
        </div>
    );
};

export default EpisodeDetails;

But as of V6, this approach no longer works. The URL pathname updated correctly (ie, /episodes/2), but the component isn't rendered for the path.

What would be the V6 equivalent to what I'm trying to accomplish? The documentation doesn't make this very clear.

1 Answers

It's odd you declared a route match param in your v5 code for the episode number and then didn't use it. In react-router-dom v6 you can create a wrapper component to "sip" the id match param and pass along the specified episode number.

const EpisodeWrapper = ({ episodes }) => {
  const { id } = useParams();
  <EpisodeDetails episode={episodes[id]} />
}

...

<Route
  path="/episodes/:id"
  element={<EpisodeWrapper episodes={this.state.episodes} />}
/>
Related