Assume my App component looks like:
import { Form } from "react-final-form";
myInitData = {
firstName: "akira",
lastName: "fubuki"
}
render() {
return
<Form
initialValues={myInitData}
onSubmit={this.handleSubmit}
validate={this.validate}
>
{({handleSubmit, submitting, values}) => (
<MyComponentOuter
someProp1={100}
someProp2={200}
/>
)}
</Form>
}
Furthermore, I have some component MyComponentInner within MyComponentOuter so the hierarchy is App => MyComponentOuter => MyComponentInner
MyComponentInner looks like:
class MyComponentInner extends Component {
componentDidMount() {
console.log(????) //how do i get access to firstName here..?
}
render() {
return (
<label>first name</label>
<Field
name="firstName"
component="input"
type="text"
/>
)
}
}
My questions are:
a) How does react-final-form's component get access to "firstName" property automagically? (no props were passed to it explictily).
b) I want to access the same firstName value within MyComponentInner; what's the syntax, for example, if i want to console.log firstName.
a) It uses React context. The <Form>
component holds a final-form
object that manages all your form state for you, and the <Field>
component uses context
to talk to the form state.
b) Something like this would do it. The render function given to Field
is provided with all of these FieldRenderProps
.
<Field name="firstName">
{
({ input } /* FieldRenderProps */) => {
console.log(input.value)
return null // render nothing (this is a render function)
}
}
</Field>