I am trying to pass props to a component, Location, using React router as a url parameter, however I am getting a type error because props.match.params.location is undefined. I am passing the location in the url Link of the Locations component and when I click on this link in the browser, it redirects to the correct url with the correct parameter:
http://localhost:3000/locations/tokyo
However this is triggering this error:
Uncaught TypeError: Cannot read properties of undefined (reading 'params')
at Location (Location.js:10:1)
App.js:
class App extends React.Component {
render() {
return (
<div className="App">
<AppNavbar />
<Routes>
<Route path="/" element={<Dashboard />} />
<Route path="/stock-levels" element={<StockLevels />} />
<Route path="/locations" element={<Locations />} />
<Route path="/locations/:location" element={<Location />} />
</Routes>
</div>
)
}
}
export default App;
Locations.js:
import {Link} from "react-router-dom";
function Locations() {
const locations = ["tokyo", "location2", "location3", "location4", "location5", "location6", "location7", "location8"]
const locationList = locations.map(location => {
return <div className="location-container">
<Card className="location-card">
<CardTitle><Link to={`/locations/${location}`}>{location}</Link></CardTitle>
</Card>
</div>
})
return (
<>
<h1>Locations</h1>
{locationList}
</>
)
}
export default Locations
Location.js:
function Location(props) {
//Make location equal to the location passed via route
const location = props.match.params.location
return (
<>
<h1>Location</h1>
<h2>{location}</h2>
</>
)
}
export default Location
As far as I can tell, with how the routes are configured and the link url:
<Link to={`/locations/${location}`}>
This should be passed as props.
Thanks for any help!