19

My react router works fine.. but I would like get the date from the Path as the title which expects a string.

  <Route exact path="/meeting/:date"
              breadcrumb="Meetings"
              title={DATE}
              component={(props) => (
                <FooComponent
                  date={props.match.params.date} />
              )}
            />

thanks

Embet Isit
  • 311
  • 1
  • 3
  • 12
  • 1
    If you use v4, As I daw in docs, the only place where you can extract url params is in the wrapped component, such as you used in FooComponent. Can you share the purpose of title as Route prop? maybe you should replace your title logic to somewhere else. – Yossi Jan 03 '18 at 21:36

3 Answers3

33

There is a new api in react-router-dom 5.1

https://github.com/ReactTraining/react-router/releases/tag/v5.1.0

import {useParams} from "react-router-dom";

function MyComponent(){
    const {date} = useParams()
}

Ihsan Müjdeci
  • 914
  • 1
  • 9
  • 14
14

In your initial component, set the path that loads your route. By adding /:date to the end of your route, that string can be accessed by calling props.match.params.date inside that routes component.

<Route exact path="/meeting/:date" component={DateComponent} />

In the component that the route renders, use props.match.params.date to access your string from path

Class DateComponent extends React.Component{
  render(){
    return(
      <h2>{this.props.match.params.date}</h2>
    )
  }
}

https://reacttraining.com/react-router/web/api/match

MEnf
  • 1,482
  • 1
  • 12
  • 18
  • 2
    This solution is for React-router v4, if you're using version 5, please refer to Ishan Mujdeci's answer below – MEnf Jul 23 '20 at 19:20
0

I use Helmet for that, it allows you to update the title, meta, scripts and basically anything related to the header.

Once you install it, just add the following code to FooComponent or to a common parent component.

<Helmet>
  <title>{props.match.params.date}</title>
</Helmet>
Crysfel
  • 7,926
  • 3
  • 33
  • 41