I am trying to create a Formik
form in a Gatsby site using the withFormik
higher order component (rather than use a render prop).
Here is a simplified version of my code:
import React from 'react'
import { withFormik } from 'formik'
const TestPage = ({ handleChange, values }) => (
<div>
<input
type="email"
name="email"
placeholder="Email"
onChange={handleChange}
value={values.email}
/>
</div>
)
const FormikTest = withFormik({
mapPropsToValues() {
return {
email: 'test@test.com',
}
},
})
export default FormikTest(TestPage)
So far, everything works just as a I want. However, I am hitting a problem when it comes to setting up a conditional argument for the email field in the mapPropsToValues
object. You can see what I am trying to do by watching about 1 minute of this tutorial (it’s set to the right starting time): https://www.youtube.com/watch?v=yNiJkjEwmpw&feature=youtu.be&t=717
The problem is that I can’t figure out how I would send props to the mapPropsToValues using Gatsby. I don’t have access to render
like in that tutorial.
In other words, in Create React App, you can do something like the following:
const FormikTest = withFormik({
mapPropsToValues({ email }) {
return {
email: email || '',
}
},
})(TestPage)
render(<FormikTest email="test@test.com />, document.getElementById('#root'))
But I don’t have access to render
in Gatsby or a <FormikTest />
component.
Any idea, therefore, how I could pass in props to mapPropsToValues
so that I could conditionally set initial values for the email form using Gatsby?
Thanks.
NOTE
I have created a simple Codesandbox version which has just one page using Formik. Here is the link: https://codesandbox.io/s/gatsby-starter-default-270gs?fontsize=14
And here is the code for that page:
import React from "react"
import { withFormik } from "formik"
const IndexPage = ({ handleChange, values }) => (
<div>
<input
type="email"
name="email"
placeholder="Email"
onChange={handleChange}
value={values.email}
/>
</div>
)
const FormikTest = withFormik({
mapPropsToValues() {
return {
email: "",
}
},
})
export default FormikTest(IndexPage)