Referencing
Reference types
There are two kinds of referencing - component and element references.
Component reference returns you the React.Component instance (i.e. <Form> or <CustomField>). Element reference returns you an HTMLElement instance rendered by the component (i.e. <form>, <input> or <select>). Both are useful for different scenarios and can be accessed as described below.
Form
Component reference
class MyForm extends React.Component {
componentDidMount() {
console.log(this.formRef) // Form component
console.log(this.formRef.innerRef) // <form> element
this.formRef.validate() // access internal methods
}
render() {
return (
<Form ref={form => this.formRef = form} />
)
}
}Inner reference
Reference the actual <form> element by providing the innerRef prop to the Form component:
You can also access the inner reference by referencing the
Formcomponent and taking itsinnerRefproperty:this.formRef.innerRef. This is the same as providingForm.props.innerRefdirectly.
Field
Component reference
Reference the field component by providing the ref prop.
Inner reference
To reference the actual form element behind the field use innerRef prop.
Beware that
innerRefwill always reference the component whereField.props.fieldPropsget destructed. You must always propagate the essential field props to the actual form element for both proper functioning and referencing.
innerRefwill not work if the form element is returned by another React Component (for example, when usingstyled-components). See the Nested element node reference example to handle those scenarios.
Nested element node
When using third-party libraries which wrap the plain form components in their own components you need to map innerRef explicitly to return the reference to the HTMLElement.
Do so by accessing an innerRef prop inside your custom field component declaration:
Do not be confused, as
StyledInput.props.innerRefis the prop expected bystyled-components,whileInput.props.innerRefis the prop (a function) passed to the custom field component from thecreateField()wrapper. Different third-party solutions may expose different interface to accept the inner reference function.
Last updated