How to access child state in react?

javascript, reactjs

Solution

I have done similar thing in a project by passing state of parent as a prop in child to access child component data in parent component for form elements.

In your case if you send component's state in its child as a prop and each child use state of parent like this.props.state.variablename and not this.state.variablename. You will have control on child components' states / data.

Sending state to childrens from form component using this.prop.children as a prop is not straight forward. Below link helps in doing this.

https://stackoverflow.com/a/32371612/1708333

Example:

Parent component:

<FormFields
    state={this.state}
    _onChange={this._onChange}
/>

Child component

<Input
    name="fieldname"
    value={this.props.state.fieldname}
    type="text"
    label="Lable text"
    validationMessage={this.props.state.validationMessages.fieldname} 
    onChange={this.props._onChange}
/>

Let me know if you need more information.

Problem

I have made my own form component with render() method looks like this: ``` render() { return ( <form onSubmit={this.onSubmit} ref={(c)=>this._form=c}> {this.props.children} </form> ) } ``` Notice that children are rendered here as `{this.props.children}`, so the user can use this component like this: ``` <Form onSubmit={this.submit} > <Input name={"name"} id="name" labelName="Ime" placeholder="Unesite ime" type="text" > <Validation rule="required" message="Ovo je obavezno polje"/> </Input> <Input name={"email"} id="email" labelName="Email" placeholder="Unesite email adresu" type="text" > <Validation rule="required" message="Ovo je obavezno polje"/> <Validation rule="email" message="Ovo je nije valjana email adresa"/> </Input> <button type="submit" value="Pošalji" >Pošalji</button> </Form> ``` I would like to check the state of each `Input` component (to get its validity) inside `onSubmitMethod()`. ``` checkValidity() { var sefl = this; this.props.children.map((child) => { if (child.type.name === "Input") { //How to get state of child here } }); } onSubmit(event) { event.preventDefault(); var obj = serialize(this._form, { hash: true }); const validityOfForm = true; //hardcoded for now this.checkValidity(); this.props.onSubmit(obj, validityOfForm); } ```

Original source

Related problems