In React-Router-Dom V6 Preview I am having issues passing the parameters to a component. Here is index.js file with all the routes.
<BaseLayout>
<Routes>
<Route path = "/" element = {<App />} />
<Route path = "/add-book" element = {<AddNewBook />} />
<Route path = "/name" element = {<Name />} />
<Route path = "/books/:id" element = {<BookDetail />} />
</Routes>
</BaseLayout>
The problem is when I go to BookDetail I cannot access the parameters using
this.props.history.match.params.id
class BookDetail extends Component {
constructor(props) {
super(props)
}
componentDidMount() {
console.log(this.props) // this.props is empty object
}
render() {
return (
<h1>BookDetail</h1>
)
}
}
Even this.props is an empty object.
And NO for this project I cannot use hooks.
UPDATE (SOLUTION):
import React, { Component } from 'react'
import { useLocation, useNavigate, useParams } from 'react-router-dom'
class BookDetail extends Component {
constructor(props) {
super(props)
}
componentDidMount() {
// this.props is always empty object
console.log(this.props.params.id)
}
render() {
return (
<h1>BookDetail</h1>
)
}
}
const withRouter = (Component) => (props) => {
const history = useNavigate();
const location = useLocation();
const params = useParams();
return <Component params = {params} history={history} location={location} {...props} />;
};
export default withRouter(BookDetail)