...

/

Learning Just Enough React

Learning Just Enough React

Get familiar with the usage of React in our Ruby application.

We’ve validated our Webpack setup, but we still don’t have the full picture of what is going on. What is a .jsx file, and what is the odd syntax inside app/javascript/packs/hello_react.jsx? We can answer these questions by talking about what React is and why we’re using it.

In the previous lesson, we stated that React is a view library for JavaScript. Like the .erb files we’ve been using, React dynamically renders HTML. Unlike ERB, React does this in the browser and it is optimized to do it quickly. Since the selected pay type will only affect a small part of our page, it will make for a better user experience to have React rerender that part of our page rather than having the server re-render the entire thing.

React is more than just a library with some handy functions we can call, though. It’s actually a mini-framework that includes extensions to JavaScript to make our work easier. Once we understand how to use those extensions, our job of creating a dynamic payment details form will result in easy-to-understand code that’s also easy to manage thanks to Webpacker.

The core concept in React is components. A component is a view backed by some sort of state. When the state changes, the view rerenders. The view can behave differently depending on the current state inside the component. For us, we’ll track the currently selected pay type as our state and have our view render different input tags based on that.

We could certainly accomplish all of this using React’s JavaScript API. However, the resulting code would be verbose, hard to follow, and hard to maintain. We mentioned React’s extensions to JavaScript, which is JSX. JSX allows us to intermix JavaScript code and HTML-like markup in one file. The result might look a bit odd at first, but it’s quite convenient for implementing components.

React provides a compiler from JSX to JavaScript, and Webpack can use that compiler as part of its build process. Let’s learn what JSX is and what it can do by replacing our existing pay-type drop-down with a React component that behaves the same way.

Creating a React-powered drop-down

To get a ...