Creating context in React
Let's learn how to place the context in react.
We'll cover the following
Let’s look at how our React page changes with context. Creating a context and reducer in React involves a few steps:
- Create the context.
- Declare the reducer with a default state.
- Optionally fetch starting data.
- 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 Purchased”, and “Current Tickets Cost”, and the “Clear Tickets” button. We’ll put them back in the React components in a moment.
It may seem strange that we haven’t discussed authentication much considering that most apps will involve authentication and that handling authentication can be challenging. That said, we’re not making a single-page application and, for what we’re doing, existing Rails authentication works. ActionCable calls from controllers track the Rails user session, as do any server calls we’ve been making from our Stimulus and React code to the Rails server. So, for these apps, we can handle authentication in any server-side-Rails in any way we want.
Let’s discuss the code changes top-down, starting from the pack entry point and moving down to the seat. After we see all the changes in the components that use the context and reducer, we’ll look at the code in the context and reducer.
First, we need to use the currently unbuilt App
component as the top-level component in our Webpacker entry point, instead of Venue
. This just swaps out the names:
Get hands-on with 1400+ tech skills courses.