Reputation: 4617
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.
Upvotes: 0
Views: 2025
Reputation: 21
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 (
);
}
}
Upvotes: 0
Reputation: 222369
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.
Upvotes: 2