I have the following URL: http://localhost:4400/skills/3
In my react component I then have:
constructor(props) {
super(props);
this.state = { skill_id: props.match.params.skill_id };
}
....
const mapStateToProps = (state, ownProps) => {
return {
skill_id: state.skill_id,
ratingsBySkillId: state.rating.by_skill_id.find(el => el.skill_id === skill_id)
};
};
The problem is state.skill_id
is not available in mapStateToProps? Why? How can I use params in mapStateToProps?
To get path params in React Router, we can use the useParams hook. We create the Child component that calls the useParams hook to return an object with the route params in the URL. And we render the value of the id param on the page. In App , we have 2 links that goes to routes with different id param values.
Getting the URL params In React router v4, you can access it using the props.match.params.id . In class-based components, you can access it like this. import React, { Component } from "react"; class Users extends Component { render() { const { id } = this.
One solution to it is using useParams inside the component and while you access the state using connect it's fine. Finally, you use that selected piece of data as in your component, where you get it from the props directly now.
Using react-router-dom v6 import { useParams } from "react-router-dom"; const Something = (props) => { let { id } = useParams(); useEffect(() => { console. log(`/something/${id}`); },[]); // ..... } A quick and exact solution. Thanks for the details.
This ended up working:
const mapStateToProps = (state, ownProps) => {
const skill_id = ownProps.match.params.skill_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