s-leg3ndz
s-leg3ndz

Reputation: 3528

React Router url with params

I use React Router on a MeteorJS framework.

I would like create new slug with /blog/:slug, but no result. My PostItem component :

class PostsListItem extends Component {

  render() {
    return (
      <li className={this.props.post.draft ? 'is-drafted' : ''}>
        <Link to={`/blog/${this.props.post.slug}`}>{this.props.post.title}</Link>
        <p>{this.props.post.description}</p>
      </li>
    );
  }

}

My routing :

class Layout extends React.Component {
  render() {
    return (
      <Router>
        <div>
          <Header />
          <main className="l-main">
            <Switch>
              <Route exact path='/' component={Home} />
              <Route path='/blog' component={Blog} />
              <Route path='/blog/:slug' component={Article} />
              <Route path='/about' component={About} />
              <Route path='/contact' component={Contact} />
              <Route component={NotFound} />
            </Switch>
          </main>
          <Footer />
        </div>
      </Router>
    );
  }
}

And my Article components (for display my /blog/:slug url) :

function Article(props) {
  return <h1>{props.match.params.name}</h1>
}

I don't understand why my page don't display. If i test /blog/test-slug, i see the parent route : <Route path='/blog' component={Blog} />

Anyone have any idea ?

Thank you community !

Upvotes: 0

Views: 778

Answers (1)

Bj&#246;rn Hei&#223;
Bj&#246;rn Hei&#223;

Reputation: 1728

Your problem is that you're doing this:

<Route path='/blog' component={Blog} />
<Route path='/blog/:slug' component={Article} />

instead of this:

<Route exact path='/blog' component={Blog} />
<Route path='/blog/:slug' component={Article} />

The router is searching for the first matching URL. And if you're not giving the "exact" attribute, everything with "/blog" matches. Doesn't matter what comes after that.

Upvotes: 1

Related Questions