React JS: How to define the states of grandchildren

advertisements

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!


You can't pass state of ancestor component to descendant component by state. You can do it by props but it leads to passing props many levels down. There's also possiblity with context but it's not good way too.

The best way is to use either flux or redux. I prefer redux and in redux you can get the variables that your object needs from one store by using connect method.

https://github.com/reactjs/react-redux/blob/master/docs/api.md

check also these videos