Compound Components in React Using the Context API

Web Design

Design & Dev / Web Design - 22 Views 0

Compound components in React allow you to create components with some form of connected state that’s managed amongst themselves. A good example is the Form component in Semantic UI React.

To see how we can implement compound components in a real-life React application, we’ll build a compound (multi-part) form for login and sign up. The state will be saved in the form component and we’ll put React’s Context AP to use to pass that state and the method from the Context Provider to the component that needs them. The component that needs them? It will become a subscriber to Context Consumers.

Here’s what we’re building:

See the Pen React Compound Component by Kingsley Silas Chijioke (@kinsomicrote) on CodePen.

Here’s a rough outline that shows how the following steps fit together:

Form is the provider with state, Form Panel is the consumer receiving state, Panel displays the panel based on the state, and Signup and Login render the form views in the Panel.

Before treading any further, you may want to brush up on the React Context API if you haven’t already. Neal Fennimore demonstrates the concept in this post and my primer on it is worth checking out as well.

Step 1: Creating context

First, let’s initialize a new context using the React Context API.

const FormContext = React.createContext({});
const FormProvider = FormContext.Provider;
const FormConsumer = FormContext.Consumer;

The provider, FormProvider, will hold the application state, making it available to components that subscribe to

Read from CSS-Tricks