Multiple path names for a same component in React Router

I have a Search class component, which takes a YouTube channel Id, and returns info on the public videos in the uploads playlist for this channel.

The route to this component is declared as:

<Route exact path=”/channelvideos/:channelId” render={ (props) =>
<Search channelId={props.match.params.channelId}/>
} />

On the UI side, there is a fixed link and dynamic links which use this component. The fixed link uses my YouTube channel Id, and it’s always visible, it can be clicked on at any time..

The UI for the fixed link is:

<Link to={`/channelvideos/${process.env.REACT_APP_CHANNEL_ID}`}>Hoàng Kỳ Channel</Link>

where process.env.REACT_APP_CHANNEL_ID holds my YouTube channel Id.

The UI for the dynamic links is similar:

<Link to={`/channelvideos/${}`}>{item.title}</Link>

( The Search component will have to look in this.props for channelId ).

The problem: clicking on a dynamic link retrieves videos for that channel, and that’s correct. Now, click on the fixed link ( i.e. the link with label Hoàng Kỳ Channel ) — NOTHING HAPPENS!

This is because Search is still in the DOM; while componentDidMount() needs to run!

I’ve chosen the solution suggested in the following post And so, the route is modified to:

<Route exact path=”/channelvideos/:channelId” render={ (props) =>
<Search channelId={props.match.params.channelId} key={props.match.params.channelId}/>
} />

It has key={props.match.params.channelId} added.

This means that old Search will unmount, a new Search will mount, and componentDidMount() fires: the entire new component rendered. Fetching of videos info takes place within componentDidMount(). New content replaces existing content, so I don’t think re-rendering the entire component is a performance penalty?

Comming from Delphi, PHP etc… background, I am still getting my head around React, Redux etc… I’m not certain if this is the most appropriate solution. Refactoring will possibly take place as I go along… For now, I settle for this solution.

One thought on “Multiple path names for a same component in React Router”

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: