I'm trying to change the value of a this.state.id
with an <input>
tag value, when I click on a <a>
tag as follows:
{this.state.json[1].map(i => (
<tr>
<td>{i.cin}</td>
<td>{i.nom}</td>
<td>{i.prenom}</td>
<td>
<a onClick={() => this.state.click(i.id)} >
<input value={i.id} hidden></input>
Create a New Folder
</a>
</td>
</tr>
))}
but the console says this.setState is not a function
. This is my component:
constructor(props)
{
super(props);
this.state = {
json:JSON.parse(props.data),//data received from a laravel controller used to
implement the page.
objet: '',
id: '',
click: function(id){
var a = id;//a is an integer
alert('hitting waypoint 1');//clear hit
this.setState({//error
id: a,
}).bind(this);
alert('hitting waypoint 2');//not alerting
alert("id = " + this.state.id)//not alerting
}
};
this.onChangeValue = this.onChangeValue.bind(this);
this.onSubmitButton = this.onSubmitButton.bind(this);
}
I think the larger issue here is that you should probably not have this function within your component's state
. If you declare it similar to your other handlers (onChangeValue
and onSubmitButton
) and bind like you did in the constructor, the function will probably work correctly.
If, however, you wish to keep the function inside state
, changing it to an arrow function will probably solve the issue. Also, as a best practice, you should change the use of var
to let
or const
.
Your improved function could look like this:
click: (id) => {
const a = id;
alert('hitting waypoint 1');
this.setState({
id: a,
});
alert('hitting waypoint 2');
alert("id = " + this.state.id);
}
As an aside, setState
is asynchronous, so the last alert (this.state.id
) may not return what you think it will. If you want to use the new id directly after you set it, you should use the const a
from earlier to guarantee that it has the correct value. Using state is (generally) better left to the render
function.