Creating a form context

Now that we understand the React context, we are going to create a context for our generic form components. Let's carry out the following steps:

  1. Let's start in Form.tsx by adding the createContext function to the React import statement:
import { FC, useState, createContext } from 'react'; 
  1. Next, we'll create interface for our context just below the Values interface:
interface FormContextProps {
values: Values;
setValue?: (fieldName: string, value: any) => void;
}

So, our context will contain the form values and a function to update them. 

  1. Let's create the context just below this:
export const FormContext = createContext<FormContextProps>({
values: {},
});

Notice that we are required to pass in an initial value for the context, which is why we made the setValue function prop optional.

That completes the creation of the form context.

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

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