Want more egghead?

This lesson is for members. Join us? Get access to all 3,000+ tutorials + a community with expert developers around the world.

Unlock This Lesson

Already subscribed? Sign In

Autoplay

    Conditionally Render a React Router v4 Route with the Switch Component

    Joe MaddaloneJoe Maddalone

    We often want to render a Route conditionally within our application. In React Router v4, the Route components match the current route inclusively so a “stack” of Routes will all be processed. To render a single Route exclusively we can wrap them in the Switch component to render the first Route that matches our current URL.

    reactReact
    15 - 16
    react-routerReact Router
    ^4.0.0
    Code

    Code

    Become a Member to view code

    You must be a Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson
    Transcript

    Transcript

    00:00 Here in our application, we've got a series of links, each pointing to routes that we've defined. We can go ahead and go to the Home, About, Contact, and everything's working just fine. Let's say that I want to create another route here that is going to be dynamic.

    00:14 I'm going to pass in itemID, break this out a little bit. What I want to do is, out of the match data, I want to go ahead and output item, and then we'll draw up the match.params.itemID right there. We're here on our Home path, everything's fine.

    00:34 I'm going to go to About, and what we'll see is that the About route is rendering, but the itemID route is rendering as well, because it's considering the About parameter in the URL to be our itemID. To solve that, we can bring in the switch component. Then we'll wrap our routes in the switch component, which will only render the first route that is a match.

    01:02 Now if we go to our home, everything's working, About, everything's working, and Contact, everything is working. If we want to go ahead and go to itemID 123456, we have our itemID.

    Discuss

    Discuss