Skip to content

React Training

Ryan Collins edited this page Oct 3, 2016 · 36 revisions

React Demonstration / Training

On October 3, 2016, we are holding a live demonstration of coding with React.

Here is a link to the Demo.

During the demo, Ryan Collins and Andreas Daimainger will be talking about React and all of the details of the setup of our projects. Ryan will be live coding one of the Udacity Alumni Web App's components to demonstrate how powerful and easy React and the tooling is.

Topics

Terminology

React

React is a declarative library made by the folks at Facebook that makes building complex web and mobile user interfaces a breeze. React is not an MVC library, as it is only concerned with the view. It allows you to describe your UI declaratively in a tree-like structure and makes it possible to build highly reusable UI components. React exists only to do one thing and do it really well, which is to render HTML to the DOM.

React abstracts away all of the tricky and expensive DOM operations with what's known as the Virtual DOM. The Virtual DOM is an in memory representation of the real DOM and React takes care of all the complexity of updating the DOM when things change.

Thinking in React

Facebook has an article called Thinking in React that talks about the process of building UI with React.

The general idea is that you break down your User Interface into components:

The first thing you'll want to do is to draw boxes around every component (and subcomponent) in the mock and give them all names. If you're working with a designer, they may have already done this, so go talk to them! Their Photoshop layer names may end up being the names of your React components!

When we get into the demonstration, we will talk about the process of breaking down our mockup into components and containers. This article is a must read.

JSX

JSX is a fantastic syntax that makes writing React very fun and easy. Just like with HTML, JSX lets you describe the structure of your UI as a Tree or Graph of connected nodes. It is yet another abstraction that takes you further away from the metal, so to speak, and lets you declaratively describe your UI.

Each JSX component must have only one parent DOM Node.

React DOM Tree

// Good
const Component = () => (
  <div>
    <h1>Hello World</h1>
  </div>
);
// Bad
const Component = () => (
  <div><h1>Hello World</h1></div>
  <span>Oops, no parent node</span>
);

JSX gets compiled into regular JavaScript objects that React can understand and render HTML from. For example

// JSX
const App = () => (
  <Form>
    <Form.Row>
      <Form.Label />
      <Form.Input />
    </Form.Row>
  </Form>
);
// Gets compiled into:
const App = (
  React.createElement(Form, null,
    React.createElement(Form.Row, null,
      React.createElement(Form.Label, null),
      React.createElement(Form.Input, null)
    )
  )
);

A few things to note. Almost all html is valid React JSX. However, you cannot use the class keyword, so you will see people using className, which React converts into class.

<h1 className="my-class">Hello World</h1>

className is referred to as a property, and as a React developer, you can use the built in properties and even define your own. A property is any JavaScript value, i.e. String, Object, Array, etc.

<h1 className="my-class" fooBar={myObject} style={{ display: 'none' }}>Hello World</h1>

JSX gets really fun to write. For more, I definitely recommend the AirBnb React Styleguide. In fact, with our ESLint setup, we have this very style guide enabled.

More Resources on JSX

Containers (Higher order components)

  • State: Containers sit on top of other components and take care of managing state for their children components.
  • Component Lifecycle

React Container Life Cycle

  • Components Components are the bits and pieces of your application. They are reusable bits of UI that take properties and render HTML. They are literally just JavaScript functions.

It is recommended that when you create a component, the component is Stateless meaning that it does not handle any of its internal state. These components are called stateless functional components

  • Stateless Functional Components: Take props and render UI. Uses JSX and the virtual dom to make building UI very declarative. Pure functionsPure Functions.
const LoadingIndicator = ({
  isLoading,
  message,
}) => (
  <Box
    align="center"
    justify="center"
    className={styles.loadingIndicator}
  >
    {isLoading &&
      <Box
        align="center"
        justify="center"
      >
        <Heading tag="h2" align="center">{message}</Heading>
        <Spinning />
      </Box>
    }
  </Box>
);

LoadingIndicator.propTypes = {
  isLoading: PropTypes.bool.isRequired,
  message: PropTypes.string.isRequired,
};
  • If you need to have internal state, you can also use a Class Component. With ES6, arrow functions do not create Lexical Scope, so you would never reference this within one, but with a Class Component, you need to be wary of this. That is outside the purview of this demo, but check below for more resources.
class LoadingIndicator extends Component {
  render() {
    const {
      isLoading,
      message,
    } = this.props;
    return (
      <Box>
        {... same as above}
      </Box>
    );
  }
}
  • Pages / Routes Pages map directly to routes. They exist only to make the organization of large applications easier. Most of the time, a Page will have a child container and that's all. When using React Router, a library that makes it possible to have client-side routing with React apps, you will point your routes to a Page.
<Route path="/create-event" component={Pages.CreateEventPage} />

Redux

The main purpose of Redux is to predictable manage state in your application. We are using it extensively because we believe that it simplifies the process of building web applications and because it eliminates runtime exceptions almost completely when done correctly.

Redux itself is a tiny JavaScript library that literally only has 6 functions in the entire API. Redux differs from traditional MVC in a few big ways. It combines Functional Reactive Programming, immutable data and the Elm Architecture into a powerhouse of a library.

The three principles of Redux are

  1. The state (data) of your whole application lives in a single JavaScript Object within a single Store.
  2. The data in your application is immutable, i.e. once set to a value cannot be changed.
  • To change your state, you use dispatch actions that describe the mutation.
  1. The only way to change your data is through a Pure Function known as a Reducer function.

The main principle of Redux is that all of the data in your app lives in one immutable object, which is maintained in a Singleton known as the Redux Store. Having all of your application's State (data) in one place simplifies things greatly.

Where Redux difers from MVC is it does not allow you to set data directly. In other words, the data in your application needs to be immutable, i.e. not able to change values once set.

  • Action Creators Action creators are functions that take data and return actions, which are plain JavaScript objects.
// An example using ES5 functions
function handleErrors(errors) {
  return {
    type: HANDLE_ERRORS,
    errors,
  }
}
// An example using ES6 fat arrow functions
// And Object Literal Expressions
const handleErrors = (errors) => ({
  type: HANDLE_ERRORS,
  errors,
});
  • Reducer Functions The job of the reducer function is to take your state, an action and return your next state. You can think of this a lot like how the JavaScript Array.prototype.reduce works.
const landingReducer = (state = initialState, action) => {
    switch (action.type) {
      case types.HANDLE_ERRORS:
        return update(state, {
          errors: {
            $set: action.errors,
          },
        });
   }

NOTE: here we are using the React Addons Update function to ensure that our state mutation is immutable. You will also see people use Immutable.js and also Object.assign which all accomplish the same thing.

  • State Management

Articles About Functional Programming

Webpack

  • Loaders
  • Babel
  • ES6 - Never write the word var or function again.
  • Devtools
    • React Devtools
    • Redux Devtools
    • ESLint (You can also set this up in your editor to show you errors)
    • React Editor Plugins: Most editors have plenty of great packages for React and JSX. We can send you a list of the ones we use, if you'd like.

Demonstration

For the demonstration, we will be creating a part of the actual alumni application. The part that we are going to be working on is the Single Post view, for viewing the content of one of the articles posted on the site.

The goal of the demonstration is to show how you go about creating UI with React and the tooling. We will also be discussing the basics of React and the React ecosystem as a whole.

Below is

Clone this wiki locally