Creating a form context provider

Now that the form context is created, let's use its Provider component to give the children components of the form access to it:

export const Form: FC<Props> = ({ submitCaption, children }) => {
const [values, setValues] = useState<Values>({});
return (
<FormContext.Provider
value={{
values,
setValue: (fieldName: string, value: any) => {
setValues({ ...values, [fieldName]: value });
},
}}
>
<form noValidate={true}>
...
</form>
</FormContext.Provider>
);
};

Notice how we create the new values object using the spread syntax (...).

The spread syntax expands the properties in the object that is referenced after the dots. It can also be used on arrays to expand the elements in the array.

So, ...values will expand the values for each field and because we have put [fieldName]: value at the end of the object literal, it will override the previous value from the values object.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.254.133