Last active
August 4, 2020 09:31
-
-
Save senorgeno/b18a692af6dc6815edfc62f442596efe to your computer and use it in GitHub Desktop.
DynamicUserForm
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React from 'react'; | |
import { graphql, useStaticQuery } from 'gatsby'; | |
import ContactForm from './DynamicUserForm'; | |
const ContactUs = () => { | |
const { contactPage } = useStaticQuery( | |
graphql` | |
query getContactForm { | |
contactPage(slug: {eq: "/contact-us/"}) { | |
id | |
title | |
content | |
formFields { | |
edges { | |
node { | |
id | |
name | |
required | |
sort | |
title | |
type | |
options | |
} | |
} | |
} | |
} | |
} | |
`, | |
); | |
return ( | |
<GenericLayout> | |
<ContactForm | |
id="ContactForm" | |
formData={contactPage} | |
formFields={contactPage.formFields.edges} | |
/> | |
</GenericLayout> | |
); | |
}; | |
ContactUs.propTypes = {}; | |
ContactUs.defaultProps = {}; | |
export default ContactUs; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React from 'react'; | |
import { withFormik } from 'formik'; | |
import * as Yup from 'yup'; | |
const MyForm = (props) => { | |
const { | |
values, | |
touched, | |
errors, | |
handleChange, | |
handleBlur, | |
handleSubmit, | |
} = props; | |
return ( | |
<form onSubmit={handleSubmit}> | |
{ formFields.map(({ node }) => ( | |
<input | |
type={node.type} | |
onChange={handleChange} | |
onBlur={handleBlur} | |
value={values.name} | |
name={node.name} | |
/> | |
))} | |
{errors.name && touched.name && <div id="feedback">{errors.name}</div>} | |
<button type="submit">Submit</button> | |
</form> | |
); | |
}; | |
const DynamicUserForm = withFormik({ | |
// set up intial values for fields | |
mapPropsToValues: (props) => { | |
const initialValues = {}; | |
props.formFields.map(({ node }) => { | |
initialValues[node.name] = node.default || ''; | |
}); | |
return initialValues; | |
}, | |
// basic dynamic validation with Yup | |
validate: (props) => { | |
const toValidate = {}; | |
props.formFields.forEach(({ node }) => { | |
if (node.required) { | |
toValidate[node.name] = Yup.string().required('This field is required'); | |
} | |
}); | |
return Yup.object().shape({ | |
...toValidate, | |
}) | |
}, | |
handleSubmit: (values, { setSubmitting }) => { | |
// do submit action | |
// you can hook into apollo mutaion here to then post your data to Silverstripe graphQL | |
}, | |
displayName: 'BasicForm', | |
})(MyForm); | |
export default DynamicUserForm; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment