I'm a beginner React programmer, struggling to understand how I should deal with grandchild states (or see whether it's a good idea to have grandchildren states).
My questions are...
1. Is it possible to change grandchildren via this.setState((prevState))
?
2. Is having grandchildren as states a bad idea?
To illustrate, here is the constructor of a component.
constructor(props) {
super(props);
this.state = {
input: {
example: "",
},
invalid:{
example: false
},
};
this.handleChange = this.handleChange.bind(this);
this.submit = this.submit.bind(this);
}
I see this.state.invalid
as a child, and this.state.invalid.example
as a grandchild.
Here is a JSX.
<div className="input">
<input type="text" value={this.state.input.example || ''} onChange={this.handleChange} />
{ this.state.invalid.example ? <span> This input is invalid </span> : null }
</div>
//Here are similar input fields...
<button onClick={this.submit} type="button">Submit</button>
When the onClick={this.submit}
is fired, I'd like to validate the input in the function, 'this.submit'.
submit(){
for (var key in this.state.input) {
if(!this.state.input[key]){
this.setState((prevState, key) => ({
invalid[key]:true, //This causes an error, saying that "SyntaxError: Unexpected token, expected ,"
}));
}
}
In this example, this.state.invalid.example
is supposed to be set (i.e. changed), but the code above doesn't work.
Maybe it'll be a better idea to decompose this app and make <div className="input">
a single component. Before doing so, I'd like to clarify whether it's possible to set grandchildren in this way.
Since I don't know anybody around me who is learning ReactJS, any advice will be appreciated!