Search code examples
javascriptreact-routerreact-hooksslug

/path/:id not switching view when Link is to={"/path/" + slug}


I am trying to get a specific post appear by using its slug. I have sucessfully made this happen by setting the Route path to /journal:id and Link to={"/journal" + post.field.slug}. However this is not what I want the url to look like. Any guess why the Route won't recognize the added slash?

            <Switch>
                <Route path='/journal' component={Journal} />
                <Route path='/journal/:id' component={SinglePost} />
                <Route path='/shop' component={Shop} />
                <Route path='/contact' component={Contact}/>
            </Switch>

When I click on the Link inside of Journal that should display the SinglePost component, the URL changes but the view doesn't change and I still see the Journal. This is the Link:

        <Link
            className='posts__post'
            key={post.fields.slug}
            to={"/journal/" + post.fields.slug}
        >

Solution

  • If you have multiple paths that have common parts like /journal and /journal/:id (common part is /journal) you should add attribute exact to shorter path to not stop searching for a route if only partially matched

        <Switch>
            <Route exact path='/journal' component={Journal} />
            <Route path='/journal/:id' component={SinglePost} />
            <Route path='/shop' component={Shop} />
            <Route path='/contact' component={Contact}/>
        </Switch>