I was trying to find a good example of form validation in react. I found validation by sending events from parent form to its input children, and calling validate method on each.
I've also found a method by looping through form children and calling setState
on a child after field is validated.
As far as I know these are anti-patterns and the react way is to call it through props callbacks - react.js custom events for communicating with parent nodes
Let say I have a component:
class Main extends React.Component {
...
onSubmitHandler() {
...
}
render() {
return (
<FormComponent onSubmit={this.onSubmitHandler.bind(this)}>
<InputComponent
value="foo"
validation="required"
/>
<input type="submit" value="Save" />
</Form>
);
}
}
class FormComponent extends React.Component {
onSubmit() {
// TODO: validation
}
render() {
return (
<form
onSubmit={this.onSubmit.bind(this)}
>
{this.props.children}
</form>
);
}
}
class InputComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
value: props.value
}
}
render() {
return (
<input
type="text"
value={value}
);
}
}
I can't really work it out, how should I do the validation of each input via callbacks passing through props.