Created
June 9, 2020 22:50
-
-
Save joshuat/09c5c2b047521953a7026a5bb1e12832 to your computer and use it in GitHub Desktop.
Context provider/hook for easy form management
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, { createContext, useContext, useState } from 'react' | |
const FormContext = createContext() | |
export const useForm = () => { | |
const context = useContext(FormContext) | |
if (context) return context | |
const [formData, setFormData] = useState({}) | |
const setField = (val, key) => { | |
setFormData(prev => ({ | |
...prev, | |
[key]: val, | |
})) | |
} | |
return { | |
formData, | |
setFormData, | |
setField, | |
} | |
} | |
export const FormProvider = ({ children }) => { | |
const formContextParams = useForm() | |
return ( | |
<FormContext.Provider value={formContextParams}> | |
{children} | |
</FormContext.Provider> | |
) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment