Introduction

There’s a problem with frontend development today: it’s overwhelming.

The React ecosystem is especially guilty of this: there’s React, Redux, Webpack, Babel, React Router, and on and on. Hundreds of boilerplate projects exist to make this “easier” by bundling a bunch of choices together.

“It’ll be easier to learn,” the thinking goes, “if you don’t have to make all the choices yourself.”

Instead, the opposite happens: rather than being overwhelmed by the choices, you’re now over- whelmed by the sheer amount of code that came “for free” with the boilerplate, and you have NO IDEA what any of it actually does. That’s a scary place to be.

Learning everything at once is massively overwhelming. So in this book, we will take a different approach.
We will learn Pure React.
The core concepts of React, in isolation, without Redux, Webpack, and the rest.

I’ll show you a concept, with some example code. Then (and this is the important part) you will use that concept in the exercises that follow, until it’s second nature. Rinse and repeat until we’ve covered all the core pieces of pure React – and there aren’t too many.

Why just React?

Without a solid understanding of React, learning libraries and tools like Redux and Webpack will only slow down your learning process.
learning everything at once will be slower in the long run.

How This Book Works

How Much Time Will This Take?

The basic concepts of React can be learned in a matter of days. This book covers those basics and also contains exercises after each major concept to reinforce your understanding.

Most of the exercises are short.
The principle behind them is the same as the idea behind homework in school: to drill the ideas into your head by combining repetition and problem solving.

The theme behind the whole process is this: avoid getting overwhelmed. Quitting won’t get you anywhere. Slow and steady, uh, learns the React.

Build Small Things and Throw Them Away

This is the awkward middle step that a lot of people skip. Moving on to Redux and other libraries without having a firm grasp of React’s concepts will lead straight back to overwhelmsville.

So What Should You Build?

The short answer is this: Build small, throwaway apps.

As your skills grow, low-fidelity copies of simple apps and sites like Reddit, Hacker News, and Slack make great projects.

By the end of this book you’ll be building replicas of those popular apps and more. They’ll come together quickly once you can clearly “think in components,” a skill you’ll develop as you progress through the book.

Learning With Small Projects

I believe that you can get more learning value out of small projects.
That isn’t to say that large projects aren’t valuable, but I don’t believe they’re good first projects. Start small, build a few small things, then build a bigger thing or two.

The exercises in this book are designed around that idea, to push you a little outside your comfort zone and make you think.

Environment Setup

Tools:

Knowledge

If you need to brush up on JS, here are some good (and free!) resources:

Hello World

$ create-react-app react-hello
$ cd react-hello

$ rm src/*
$ touch src/index.js
import React from 'react';
import ReactDOM from 'react-dom';

function HelloWorld() {
  return (
    <div>Hello World!</div>
  );
}

ReactDOM.render(
  <HelloWorld/>,
  document.querySelector('#root')
);

the statement import React from 'react' creates a new variable called React with the contents of the react module.
react and react-dom correspond to the names of modules installed by npm.

From inside the react-hello directory, start the app by running this command:

$ npm start

How the Code Works

ReactDOM.render:
React uses the concept of a virtual DOM. It creates a representation of your component hierarchy and then renders those components by creating real DOM elements and inserting them where you tell it.

ReactDOM.render takes 2 arguments: what you want to render (your component, or any other React Element) and where you want to render it into (a real DOM element that already exists).

ReactDOM.render([React Element], [DOM element]);

Above that, we have a component named HelloWorld.

3 JSX: What and Why

This HTML-like syntax is actually called JSX.

JSX is a syntax invented for React that looks very similar to (X)HTML.
The HTML-like syntax actually compiles down to real JavaScript.

The JSX elements you write are actually compiled down to JavaScript by a tool called Babel. Babel is a compiler that transforms code into valid ES5 JavaScript that all browsers can understand, and it’s bundled in with projects created by Create React App.

After you run npm start, a tool called Webpack is watching for files to change. When they do, it feeds those files into Babel, which turns JSX into JS, and sends it to your browser via the development server running on port 3000.

Here’s an example of a simple React component that returns some JSX:

function Hello() {
  return <span>Hello!</span>;
}

And here is the JavaScript generated by the Babel compiler:

function Hello() {
  return React.createElement(
    'span',
    {},
    'Hello!'
  );
}

Here is a slightly more complicated bit of JSX:

function SongName(props) {
  return (
    <span className='song-name'>
      {props.song.name}
    </span>
  );
}

And here is what it compiles to:

function SongName(props) {
  return (
    React.createElement('span',
    { className: 'song-name' },
    props.song.name
    )
  );
}

Your first instinct might be to avoid writing JSX because you don’t like the look of “HTML in JS.”.
All React developers use JSX, which means code that you see in the wild (on GitHub, Stack Overflow, etc.) is likely to be written with it.

Unseparated Concerns

You may find (as I did) that merging the logic and view makes your code easier to navigate, easier to write, and easier to debug. You’ll spend less time hopping between files when all the related functionality is in one place.

4 Working With JSX

Composing Components

Let’s refactor the HelloWorld
Here’s the original HelloWorld:

function HelloWorld() {
  return (
    <div>Hello World!</div>
  );
}

Your two new components should look like this:

function Hello() {
  return <span>Hello</span>;
}
function World() {
  return <span>World</span>;
}

Now, change the HelloWorld component to use the two new components you just created:

function HelloWorld() {
  return (
    <div>
      <Hello/> <World/>!
    </div>
  );
}

Wrap JSX with Parentheses

This will fail with an error:

function HelloWorld() {
  return
  <div>
    <Hello/> <World/>!
  </div>;
}

if it’s on multiple lines, I recommend wrapping it in parentheses.

Return a Single Element

This JSX:

function HelloWorld() {
  return (<Hello/> <World/>);
}

Becomes this JS:

function HelloWorld() {
  return (
    React.createElement(Hello, null) React.createElement(World, null)
  );
}

A component function must return a single element.

Wrap With a Tag

The most obvious way to return multiple elements is to wrap them in an enclosing tag, like a

or . However, it has the side effect of influencing the DOM structure.

function HelloWorld() {
  return (
    <div>
      <Hello/> <World!/>!
    </div>
  );
}

will render a DOM structure like this:

<div>
  <span>Hello</span>
  <span>World</span>
<div>

A lot of the time, this is perfectly fine. But sometimes, you won’t want to have a wrapper element, like if you have a component that returns two table cells:

function NameCells() {
  return (
    <td>First Name</td>
    <td>Last Name</td>
  );
}

Fragments

React’s answer is the fragment. This component was added in React 16.2, and can be used like this:

function NameCells() {
  return (
    <React.Fragment>
      <td>First Name</td>
      <td>Last Name</td>
    </React.Fragment>
  );
}

After rendering, the React.Fragment component will “disappear”, leaving only the children inside it.

Fragment Syntax

A special syntax that looks like an “empty tag” and is much nicer to write:

function NameCells() {
  return (
    <>
      <td>First Name</td>
      <td>Last Name</td>
    </>
  ); 
}

JavaScript in JSX

You can insert real JavaScript expressions inside JSX code:

function SubmitButton() {
  const buttonLabel = 'Submit';
  return (
    <button>{buttonLabel}</button>
  );
}

the JS inside the braces must be an expression.

“If” in JSX

Ternary operator:

function ValidIndicator() {
  const isValid = true;
  return (
    <span>{isValid ? 'valid' : 'not valid'}</span>
  );
}

Capitalize Component Names

The components you write must begin with an uppercase letter.

In JSX, a component that starts with a lowercase letter is assumed to be a built-in HTML or SVG element (div, ul, rect, etc.).

Close Every Element

DO THIS:

return <br />;
return <input type='password' ... />;
return <li>text</li>;

Exercises

Create a new app running:

$ create-react-app jsx-exercices

Open the src/index.js file and replace the contents, similar to Hello World. Fill in the rest.

import React from 'react'
import ReactDOM from 'react-dom'

function MyThing() {

}

ReactDOM.render(
  <MyThing/>,
  document.querySelector('#root')
);

1. Create a component that renders this JSX

<div className='book'>
  <div className='title'>
    The Title
  </div>
  <div className='author'>
    The Author
  </div>
  <ul className='stats'>
    <li className='rating'>
      5 stars
    </li>
    <li className='isbn'>
      12-345678-910
    </li>
  </ul>
</div>