Dharamveer Grewal
Dharamveer Grewal

Reputation: 135

Cannot read property 'someProperty' of undefined in react

I am working on an application where I pass variable values in a Navlink using state from one component to the other and then load those received values in input fields and click on submit button in that other component to do something with values. My values are received correctly and show up correctly when I alert them. But when I click submit button, it gives error,pointing at the constructor

TypeError: Cannot read property 'id' of undefined

Here is my code

class Parent extends React.Component{
    constructor(props) {
        super(props);
        this.state={id:2}
    } 

    render(){
       return(
         <NavLink 
           to={{
             pathname: '/Child',
             state: {
               id: this.state.id
             }
           }}
         >
           Edit
         </NavLink>
       )
    )
}

Where I receive the values

class Child extends React.Component{
    constructor(props) {
        super(props);

        this.state = {id:this.props.location.state.id}
        alert(this.props.location.state.id)//works fine
    }

    setId(e){
        this.setState({id:e.target.value})
    }

    addOrEdit(){ //gives error    
        alert(this.state.id) 
        //do something    
    }

    render(){
        return(
          <div>
            <form>
              <label>Id</label>
              <input value={this.state.id} onChange={this.setId.bind(this)}  type="text"/><br/>
              <input type="submit" onClick={this.addOrEdit.bind(this)} ></input>
            </form>
          </div>
        )
    }
}

Upvotes: 1

Views: 334

Answers (2)

Hagai Harari
Hagai Harari

Reputation: 2877


 this.state = {id: this.props.location && this.props.location.state && this.props.location.state.id}

Should fix your issue that caused by times that this component called without this context or this line got excuted before location set. (assuming you using withRouter for making location props be exist...)

Anyhow, and not related directly to your issue, it is bad practice to set initial value for state from props at constructor, consider manipulate state through life cycle either don't use state here and refer to props directly

Upvotes: 2

d3bgger
d3bgger

Reputation: 329

I would suggest to just use arrow functions for setId and addOrEdit.

addOrEdit = (e) => {
    // ...
}

And just call them:

onChange={this.setId}
onClick={this.addOrEdit}

https://medium.com/@machnicki/handle-events-in-react-with-arrow-functions-ede88184bbb

Also you are deriving state from prop. It is better to just use the prop directly.

https://reactjs.org/blog/2018/06/07/you-probably-dont-need-derived-state.html

Upvotes: -1

Related Questions