I'am new to react-router (v4) and I was following the tutorial until this little problem :
This code works quite well
class App extends Component { render() { return ( <Router> <div> <ul> <li><Link to="/link/value1" className="nav-link">Value1</Link></li> <li><Link to="/link/value2" className="nav-link">Value2</Link></li> <li><Link to="/link/value3" className="nav-link">Value3</Link></li> </ul> <hr/> <Route path="/link/:id" component={Generic}/> </div> </Router> ); } }
I defined a route to /link/:id with 3 links to it. Then I declare my "Generic" component like this (as a function) :
const Generic = ({ match }) => ( <div className="wrapper"> <div className="section"> <div className="container"> <h3>Menu : {match.params.id}</h3> </div> </div> </div> )
This work as expected, no problem. But now, I'd like to declare my component with the ES6 class syntaxe like this :
class Generic extends React.Component { constructor(props) { super(props); } render() { return ( <div className="wrapper"> <div className="section"> <div className="container"> <h3>Menu : {this.props.params.id}</h3> </div> </div> </div> ); } }
And here I have an error : Cannot read property 'id' of undefined
How can I access the "match.params.id" properties using the ES6 class approach?
Thank you for your help.
If you are using react-router v4, you can pass it using the render prop. Sometimes you need to render whether the path matches the location or not. In these cases, you can use the function children prop. It works exactly like render except that it gets called whether there is a match or not.
To use useParams() inside class component with react-router-dom, we can use the withRouter higher order component. import React from "react"; import { withRouter } from "react-router"; class TaskDetail extends React. Component { componentDidMount() { const { id } = this.
react-router-dom v5 If using RRDv5 if the match prop is undefined this means that BookScreen isn't receiving the route props that are injected when a component is rendered on the Route component's component prop, or the render or children prop functions.
Use {this.props.match.params.id}
If you need to pass some props to the component, use this approach:(eg)
<Route path='/home' render={(props) => <Home {...props} user = {this.state.user} />} />
In the target component you can now access both, the prop and the router parameter using this.props.user
& this.props.match.params.id
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With