Stéphane R.
Stéphane R.

Reputation: 1496

React Router v4 passing params to component

I use React Router on MeteorJS projet, and i've create new slug type /blog/:slug url and my components for this url.

But, i don't know how i can passing a props params to my component (Ex. title, description, comment, etc.). I've test to show my console.log when i go to /blog/test-slug :

Object { path: "/blog/:slug", url: "/blog/test-slug", isExact: true, params: Object }

I do not have params.

You can see my routing :

class Layout extends React.Component {
  render() {
    return (
      <Router>
        <div>
          <Header />
          <main className="l-main">
            <Switch>
              <Route exact path='/' component={Home} />
              <Route exact 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>
    );
  }
}

My Article component :

function Article(props) {
  console.log(props.match);
  return (
    <h1>{props.match.params.slug}</h1>
  );
}

And my link for acces to Article component :

<Link to={`/blog/${this.props.post.slug}`}>{this.props.post.title}</Link>

Anyone can help me about this ?

Thank you community !

Upvotes: 1

Views: 3217

Answers (1)

gouroujo
gouroujo

Reputation: 551

solution 1: create proxy page component where you add your data.

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

const ArticlePage = ({ match }) =>
    <Article slug={match.params.slug} description="..." />

const Article = ({slug, description}) =>
    <h1>{slug} : {description}</h1>

Or, solution 2 : user render callback in Route component :

<Route path='/blog/:slug' render={({match}) => (
  <Article slug={match.params.slug} description="..." />
 )} />

const Article = ({slug, description}) =>
    <h1>{slug} : {description}</h1>

Upvotes: 4

Related Questions