Reader small image

You're reading from  React 16 Tooling

Product typeBook
Published inApr 2018
Reading LevelBeginner
PublisherPackt
ISBN-139781788835015
Edition1st Edition
Languages
Tools
Right arrow
Authors (2):
Adam Boduch
Adam Boduch
author image
Adam Boduch

Adam Boduch has been involved in large-scale JavaScript development for nearly 15 years. Before moving to the frontend, he worked on several large-scale cloud computing products using Python and Linux. No stranger to complexity, Adam has practical experience with real-world software systems and the scaling challenges they pose.
Read more about Adam Boduch

Christopher Pitt
Christopher Pitt
author image
Christopher Pitt

Christopher Pitt is a principal developer for SilverStripe in Wellington, New Zealand. He usually works on open source software, though sometimes you'll find him building compilers and robots.
Read more about Christopher Pitt

View More author details
Right arrow

Chapter 5. Streamlining Development and Refactoring with Type-Safe React Components

The tool of focus in this chapter is Flow, a static type checker for JavaScript applications. The scope of Flow and what you can do with it is enormous, so I'll be introducing Flow in the context of a tool that's used to make React components better. In this chapter, you'll learn the following:

  • The problems that are solved by introducing type-safety into your React application
  • Enabling Flow in your React projects
  • Using Flow to validate your React components
  • Other ways to enhance React development using type-safety

What does type-safety solve?


Type-safety is no silver bullet. For example, I'm perfectly capable of writing a type-safe application that's riddled with bugs. It's the kind of bugs that just sort of stop happening after a type-checker is introduced that are interesting. So what types of things can you expect after introducing a tool like Flow? I'll share three factors that I've experienced while learning Flow. The Type System section in the Flow docs goes into much more detail on this topic, available at https://flow.org/en/docs/lang/.

Replacing guesswork with assurance

One of the nice features of a dynamically-typed language like JavaScript is that you can write code without having to think about types. Types are good and they do solve a lot of problems—the point I'm trying to make, believe it or not—but sometimes you need to be able to just write code without having to formally validate for correctness. In other words, sometimes guesswork is exactly what you need.

If I'm writing a function...

Installing and initializing Flow


Before you can start implementing type-safe React components, you need to install and initialize Flow. I'll show you how this is done with a create-react-app environment, but the same steps can be followed for almost any React environment.

You can install Flow globally, but I would recommend installing it locally, along with all the other packages that your project depends on. Unless there's a good reason to install something globally, install it locally. This way, anyone installing your application can get every dependency by running npm install.

To install Flow locally, run the following command:

npm install flow-bin --save-dev

This will install the Flow executable locally to your project and will update your package.json so that Flow is installed as a dependency of your project. Now let's add a new command to package.json so that you can run the Flow type checker against your source code. Make the scripts section look like this:

"scripts": { 
  "start": "react...

Validating component properties and state


React was designed with Flow static type-checking in mind. The most common use of Flow in React applications is to validate that component properties and state are being used correctly. You can also enforce the types of components that are allowed as children of another component.

Prior to Flow, React would rely on the prop-types mechanism to validate values passed to components. This is now a separate package from React and you can still use it today. Flow is a superior choice over prop-types because it performs checks statically whereas prop-types performs runtime validation. This means that your application doesn't need to run superfluous code during runtime.

Primitive property values

The most common types of values that are passed to components via props are primitive values—strings, numbers, and Booleans for example. Using Flow, you can declare your own type that says which primitive values are allowed for a given property.

Let's take a look at...

Validating event handler functions


React components use functions to respond to events. These are called event handler functions, and they're passed an event object as an argument when the React event system calls them. It can be useful to use Flow to explicitly type these event arguments to make sure that your event handler is getting the type of element that it expects.

For example, assume that you're working on a component that responds to clicks from an <a> element. Your event handler function also needs to interact with the clicked element, in order to get the href property. Using the Flow types exposed by React, you can ensure that the correct element type is indeed triggering the event that is causing your function to run:

// @flow
import * as React from 'react';
import { Component } from 'react';

class EventHandler extends Component<{}> {
  clickHandler = (e: SyntheticEvent<HTMLAnchorElement>): void => {
    e.preventDefault();
    console.log('clicked', e.currentTarget...

Bringing Flow into the development server


Wouldn't it be great if type-checking your React code were more tightly-integrated into the create-react-app development process? There's been talk of making this a reality in a future release of create-react-app. For now, you'll have to eject from create-react-app if you want this functionality for your project.

The goal of this approach is to have the development server run Flow for you whenever changes are detected. Then, you can see the Flow output in your dev server console output, and in the browser console.

Once you've ejected from create-react-app by running npm eject, you need to install the following Webpack plugin:

npm install flow-babel-webpack-plugin --save-dev

Then, you need to enable the plugin by editing config/webpack.config.dev.js. First, you need to include the plugin:

const FlowBabelWebpackPlugin = require('flow-babel-webpack-plugin');

Then, you need to add the plugin to the array in the plugins option. This array should look something...

Bringing Flow into your editor


One final option that we'll look at for validating your React code using Flow is integrating the process into your code editor. I'm using the popular Atom editor so I'll use this as an example, but there are likely options for integrating Flow with other editors.

To enable Flow capabilities in the Atom (https://atom.io/) editor, you'll need to install the linter-flow package:

Once installed, you'll need to change the executable path setting of linter-flow. By default, the plugin assumes that you have Flow installed globally, which, you probably don't. You have to tell the plugin to look in the local node_modules directory for the Flow executable:

You're all set. To verify that this is working as expected, open up App.js from a fresh create-react-app install and add the @flow directive at the top of the file. This should trigger an error from Flow and should be displayed within Atom:

The Linter will also highlight the problematic code that's causing Flow to complain...

Summary


In this chapter, you learned about why type-checking your React code matters. You also learned about Flow—the tool used to type-check React code. Type-checking is important for React applications because it removes the need to perform runtime checks of values in the majority of cases. This is because Flow is able to statically follow code paths and determine whether everything is being used as intended.

Then, you installed Flow locally to a React application and learned how to run it. Next, you learned the basics of validating property and state values of React components. Then you learned how to validate function types and how to enforce child React component types.

Flow can be used in create-react-app dev server, but you have to eject first. In future versions of create-react-app, there will likely be better integrated support for running Flow as part of the dev server. Another option is to install a Flow plugin in a code editor such as Atom, and have errors displayed right in front...

lock icon
The rest of the chapter is locked
You have been reading a chapter from
React 16 Tooling
Published in: Apr 2018Publisher: PacktISBN-13: 9781788835015
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $15.99/month. Cancel anytime

Authors (2)

author image
Adam Boduch

Adam Boduch has been involved in large-scale JavaScript development for nearly 15 years. Before moving to the frontend, he worked on several large-scale cloud computing products using Python and Linux. No stranger to complexity, Adam has practical experience with real-world software systems and the scaling challenges they pose.
Read more about Adam Boduch

author image
Christopher Pitt

Christopher Pitt is a principal developer for SilverStripe in Wellington, New Zealand. He usually works on open source software, though sometimes you'll find him building compilers and robots.
Read more about Christopher Pitt