Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access 'this.props.match.params' along with other props?

I have this code in my parent component:

<Route path='/champions/:id' render={(props) => <ChampionDetails {...props} match={this.handleMatch}/>}/>

where the match prop will be a function that retrieves data from the child component (ChampionDetails). A snippet of my ChampionDetails (child) component:

    import React, { Component } from 'react';

    class ChampionDetails extends Component {
      state = {
        champId:this.props.match.params.id,
        champData:null,
        match:false
      }

      componentDidMount(){
        console.log('ChampionDet mounted')
        this.handleChampInfo();
        console.log(this.props.match)
      }

      componentDidUpdate(){
        console.log('ChampionDet updated')
      }


      handleChampInfo=()=>{
        let champData = [];
        let id = this.state.champId
        console.log(id)
        fetch('/api/getChampion?id='+id)
          .then(data=> { return data.json() })
          .then(json=> {
            console.log(json.data);
            champData.push(json.data);
            this.setState({
              champData:json.data,
              match:true
            })
            this.props.match(true)
            // this.props.history.push('/champions/'+id)
          })
          .catch(err=>{
            console.log(err)
          })
      }

      render(){
        return(
          <div>
            <p>{this.state.champId}</p>
            {this.state.champData===null ? null:<p>{this.state.champData.roles}</p>}
          </div>
        )
      }
    }

    export default ChampionDetails;

The problem here is that if I have the match={} in my parent's route, then this.props.match.params.id will become undefined. If I remove match={} then I can retrieve this.props.match.params.id

I would like to know if its possible to be able to pass other props while still have access to this.props.match.params.id in my case.

Any help will be much appreciated!

like image 884
raylism Avatar asked Jan 09 '19 16:01

raylism


People also ask

How do I get params ID to match props?

Just create constructor i.e constructor(props) {} and inside it declare the id as a state variable to the class. Pass the value of match.params.id to the id by using id: this.props.match.params.id . Now u can access the state variable anywhere in your code and hope it solves your problem. Save this answer.

Which props should you use to match exactly the path you gave for routing?

The exact prop is used to define if there is an exactly the requested path.


1 Answers

If you're using react-router version >=4, you should be able to access the router params at any component inside the router via withRouter HOC. For instance:

import { withRouter } from 'react-router-dom';
...
export withRouter(ChampionDetails);
like image 88
Rafael Sousa Avatar answered Sep 27 '22 19:09

Rafael Sousa