Creating context in React

Let's learn how to place the context in react.

Let’s look at how our React page changes with context. Creating a context and reducer in React involves a few steps:

  1. Create the context.
  2. Declare the reducer with a default state.
  3. Optionally fetch starting data.
  4. Place the context in the JSX as a parent component.

Context is then visible to all child components inside the JSX context element.

Declaring the context

In this lesson, we’re going to recreate all the existing page logic plus the subtotal calculator, except for the part that communicates with the server via ActionCable. ActionCable’s asynchronous behavior adds complications that we’ll talk about after we cover basic logic.

To make all this work, we’re going to wrap our Venue component inside a new top-level App that will hold the context. Not only is this more consistent with the common React style, but it also allows us to separate the application logic of the Venue component from the React logistics of the application.

The code changes to make this work starts in our ERB file for the concert show page. We need to remove more HTML out of the ERB file that will go in our subtotal calculation. We’ve three div elements in app/views/concerts/show.html.erb that need to be removed: the lines “Current Tickets ...