0
constructor() {
    super();



    this.state = {

        idnum: this.props.match.params.id,
        pokemon: [],
        imgurl: '',
        abilities: [],
        types: []
    };

    this.clickHandler = this.clickHandler.bind(this);
};

clickHandler(e) {

    this.setState({
        idnum: this.props.match.params.id
    })
    console.log("passed" , this.props.match.params.id)
}

I am trying to store this.props.match.params.id which is a id number passed in as a prop into one of my states in React.js this.props.match.params.id works in my componentWillMount function that uses this id number to call a specific data from an API, but it gives me that match is undefined when I try to store it in my state.

I need this to work so that I can make the page re-render when Linking to the page with previous Id number by doing

<Link to={{ pathname: '/details/' + (parseInt(this.props.match.params.id) - 1) }}><Button onClick = {this.clickHandler }>Prev</Button></Link>

What is the way to store my this.props.match.params.id into my state?

user6792790
  • 668
  • 1
  • 7
  • 22
  • 1
    Please provide a [mcve]. – Felix Kling Oct 12 '17 at 15:53
  • when your app calls the constructor, this.props doesn't exist. you need to set the state after your component mounts, like in componentDidMount – Cruiser Oct 12 '17 at 15:57
  • Possible Duplicate [Accessing props inside constructor](https://stackoverflow.com/questions/30571875/whats-the-difference-between-super-and-superprops-in-react-when-using-e) – Mayank Shukla Oct 12 '17 at 16:00

1 Answers1

0

To access props in the constructor, you can do the following:

constructor(props) {
  super(props)
  this.state = {
    idnum: props.match.params.id
  }
}
Morleee
  • 349
  • 2
  • 8