As @benjaminadk suggested state is an object.
So you can use a for each loop, or (and that’s what I generally like) using ES6 Object syntax to iterate.
Object.keys(this.state.item).map(i => alert(this.state.item[i))
// will alert each values
You can call setState inside the map function for example:
Object.keys(this.state.item).map(
i => this.setState({ [i]: someValue }))
Please note that I use arrow function inside map so that it does not bind this.
Maybe the error you had in your function was due to the fact that you were re-binding this context.
(if your error was cannot read property state of undef it’s likely the case)
I want to find a property that doesn’t have any value and trigger an even in child element. So when the user press submit button, fields that didn’t receive any value will be marked red
this.refs.property.parentMarkError();
This how my render function for parent looks like now:
Object.keys(this.state.item).map(function (key) {
var myitem = this.state.item[key];
if (myitem == ''){
this.refs.[key].parentMarkError();}
});
Except maybe for the binding of this.
It can be slimmed down as:
Object.keys(this.state.item).map((key) => {
if (!this.state.item[key]){
this.refs.[key].parentMarkError();
}
});
Have you tried it?
On a side note using refs is (in general) not an optimal idea in react, in the docs is explained why: refs and the dom
what you want to accomplish can be done with ease, assuming your inputs are controlled components ( ie when a user type a state change in your app, instead of letting the DOM handle it).
It’s enough to have in your state a parameter for the error and pass it to the child as prop: