0

I have written a custom Input class component.

class Input extends React.Component {
  validate = () => { 
    // validation logic
  }

  handleChange = () => {this.validate()}

  render () {
    return <input onChange={this.handleChange} name={this.props.name} type={this.props.type}/>
  }
}

In a Form component I use it like this.

class Form extends React.Component {

  handleSubmit () => {
    // trigger Input validation here
  }

  render () {
    return <form onSubmit={this.handleSubmit}>
      <Input name="abc" type=""/>
      <Input name="abc" type="password"/>
    </form>
  }
}

There can be more than 20 Input component nested in Form component. My question is how do I trigger validations of Input components from the Parent Form component when the form is submitted?. Since I have a lot of Input components I need to a way to call all the validation method of every Input instance.

2 Answers 2

2

Parent component should have a ref of a child in order to access its methods:

  refs = {
    foo: React.createRef(),
    bar: React.createRef()
  }

  handleSubmit () => {
    for (const [refName, ref] of Object.entries(this.refs)) {
      const isValid = ref.current.handleSubmit();
      // ...
    }
  }

  render () {
    return <form onSubmit={this.handleSubmit}>
      <Input ref={this.refs.foo} name="foo"/>
      <Input ref={this.refs.bar} name="bar"/>
    </form>
  }

In case there are many inputs, the code could be made DRYer by automatically registering refs with respective names that match name attributes.

Sign up to request clarification or add additional context in comments.

Comments

0

Please try the below code for calling function from child components.

class Parent extends React.Component {
    triggerChildAlert(){
        this.refs.child.showAlert();
    }

    handleSubmit () => {
       this.refs.child.validate ();
    }

    render() {
        return (
                <div>
                   {/* Note that you need to give a value to the ref parameter, 
                       in this case child*/}
                   <Child ref="child" />
                   <button onClick={this.handleSubmit}>Click</button>
                </div>
            );
        }
    }


class Child extends React.Component {
    validate () {

    }

    render() {
        return (

        );
    }
 }

1 Comment

You are using the old way of creating ref which is considered legacy. See reactjs.org/docs/refs-and-the-dom.html#legacy-api-string-refs. You should use the new way as stated in the link, like user estus used in his answer above.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.