Search code examples
wordpressreactjsreact-routerwordpress-rest-api

React Router - passing Slug as a prop to child Component


I am trying to create the possibility for a page to display itself so long as the data is there - I'm using WordPress REST API and the end user will be able to create pages for themselves that obviously won't appear in the Router as I can't possibly forsee all of the pages they will eventually want to create.

The way I'm trying to resolve this is to pass something of a wildcard into react-router (picture 1).

Picture 1:
Picture 1

So, in my understanding, if the user visited my site and put in /giraffe, it would take them to the <About /> component, and would put /giraffe in the pageSlug parameter. However, it puts :slug in that parameter.

When I use the React Dev Tools, I can see that there is an element between my <App /> (top level) component and my <About /> component with no name and has parameters - see Picture 2:

Picture 2

This has a component with the following information <component location={pathname: "/giraffe", search: "", hash: ""} params={slug: "giraffe"} /> etc. Is there any way that I can pass these params into the route?

Here is how I am returning my <About /> component - Picture 3:

Picture 3

This is the first time I've used React and React-Router, so I appreciate that this may be a stupid question or I may be doing this all wrong, however I've been trawling through questions and answers for a few hours and am none the wiser. I feel like I should be able to access those parameters, but no idea.

Help?


Solution

  • From the docs:

    A route's component is rendered when that route matches the URL. The router will inject the following properties into your component when it's rendered.

    params

    The dynamic segments of the URL.

    So if your route is defined as follows:

    <Route path="/:slug" component={About} />
    

    you could access this.props.params.slug to get the parameter value.