Hands-on with React
Explore how to build a React single-page application integrated with Phoenix using websockets and channels. Understand component lifecycles, state management, and real-time data flow to create efficient real-time user interfaces.
Components in a React application
Well-factored components can be difficult to grasp without a concrete example to show the way. We’ll be working on a Phoenix application with a single-page React front-end. We’ll see examples of container components, presentation components, and how to wire them together with contexts and React Router. There will be a bit of React-specific patterns that we may not be used to, but don’t worry too much if we’re not familiar with React.
The application has several different single-purpose components. We’ll build a container component that holds a basic Phoenix Socket and a presentation component that sends and receives data from a Channel. This example will be based on a mostly complete codebase, so we can jump right into the code without worrying about setting up React.
This example has four pages and looks like the following image:
This is a single-page application; the browser will not perform a full-page reload as we navigate around it. Here’s an overview of the four pages in the application:
- Home: This page serves only static content, so it doesn’t use a Socket or Channel. The Phoenix Socket is disconnected when this page loads.
- Pings: This page receives data from the
pingtopic and displays it in atextareaelement. This page has a button that will send data to the Channel when pressed—the response from the Channel is displayed in thetextareaelement. - Other Pings: This page is a clone of the Pings page but is for the
othertopic. When this page is visited, thepingChannel is closed, and theotherChannel is joined. - Counter: This page receives data from the
pingtopic and shows the number of received messages.
The application is basic but will demonstrate how different pages can use other real-time Channels. When we run the application locally, later in ...