I have a component ViewRestaurant.js
that is part of a react-router
(using 5.2). I'm trying to access a dynamic URL parameter ("/view-restaurant/:id"
, the id
)
Snippet from App.js
(the main data loader):
return (
<Router>
<div>
<Route
exact
path="/"
component={() => (
<Main
restaurants={this.state.restaurants}
account={this.state.account}
/>
)}
/>
<Route
path="/view-restaurant/:id"
component={() => (
<ViewRestaurant
restaurants={this.state.restaurants}
account={this.state.account}
/>
)}
/>
</div>
</Router>
);
This is how I'm trying to put the Link
, snippet from Main.js
which displays a list of restaurants:
<Link
to={{
pathname: '/view-restaurant/' + key,
state: { id: key }
}}
>
View
</Link>
But when I'm trying to access what I've passed, meaning the id
, which is the same as key
in Main.js
, it doesn't work.
Snippet from ViewRestaurant.js
:
render() {
const restaurants = this.props.restaurants
console.log(restaurants[0].name) // this works.
console.log(this.state.id) // this throws the error.
// return removed for readability
}
The error: TypeError: this.state is null
According to the documentation, we should be able to create a state and pass it via link. I'm 100% sure I'm misinterpreting the documentation, but I just don't know how to solve this error.