Sharing state with React context

The state for field values lives in the Form component. However, the values are rendered and changed with the Field component. The Field component doesn't have access to the state within Form, because the state lives in the Form instance and Field doesn't.

This is very similar to the compound Tabs component we implemented in the last chapter. We shared state between the components in the Tabs compound using React context.

We are going to use the same approach for our Forms component in this section:

  1. Let's start by creating an interface for the form context in Form.tsx:
interface IFormContext {  values: IValues;}

The context just contains values that have the same type, IValues, as in our state.

  1. Let's create ...

Get Learn React with TypeScript 3 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.