Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Within mapStateToProps, how to obtain a react-router param?

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?

like image 365
AnApprentice Avatar asked Jun 23 '17 16:06

AnApprentice


People also ask

How do you get a route Param React?

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.

How do you get the router parameter in React class component?

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.

How do I use useParams in mapStateToProps?

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.

How do I get parameters in React router 6?

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.


1 Answers

This ended up working:

const mapStateToProps = (state, ownProps) => {
  const skill_id = ownProps.match.params.skill_id;
....
like image 157
AnApprentice Avatar answered Oct 13 '22 03:10

AnApprentice