{ Introduction to React. }

Objectives

By the end of this chapter, you should be able to:

  • Describe what a React component is
  • Make a simple React component with JavaScript and HTML
  • Use props to customize React components

React Prerequisites

In this course, we will be using many advanced JavaScript features, so it is important that you are comfortable with the content from Intermediate JavaScript I, Intermediate JavaScript II, Advanced JavaScript I, and Advanced JavaScript II before starting with the React content. Pay close attention to the ES2015 chapter of the Advanced JavaScript Part II course as ES2015 syntax is used frequently in this course.

If you are feeling ready, let's dive into React!

Introduction to React

React is a lightweight JavaScript library that is primarily responsible for the views that you create on your website. It is a front-end library, which means that it is (typically) run in the client's browser, rather than on the server side.

One of the key concepts in React is the use of components. A component is a reusable element that can be displayed on the web page, or a higher level component that controls view components. When you use React, you are ultimately creating components that are modular enough to be reused many times and potentially in many places in your application.

Building an Application Using Components

To solidify the idea of components, let's think about how we could design a to-do list application using react components. We want to make a to-do list app that works like our example below.

Todo List Application Gif

The app has a an HTML li element for each item in our to-do list plus a form in which users can enter new to-do items by providing a title and a description. If we were to break this app down, we might make the following components:

  1. A TodoListItem component that can be reused for each to-do item in the list
  2. A TodoListForm component that allows the user to type and submit new to-do items.
  3. A TodoListApp component that uses the TodoListItems and the TodoListForm to create the entire to-do list application.

Even in this small example, you may have noticed that we are using smaller components to build a larger component. Specifically, we are using the TodoListItem and the TodoListForm to create the TodoListApp. This concept is called composition and it is frequently used in React.

We will see more concrete component examples as we go, but it's useful to get a preview of these concepts before we get started.

Getting Started With React

Let's jump in and write our first React code! To get started, let's make sure we have the two scripts necessary for rendering a component in the DOM. The first is the React library and the second is the ReactDOM library, which is used for rendering to the DOM. These libraries are isolated as there are environments where we can use React and not have access to a DOM (like mobile development, game development, or even command line scripts).

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>
    <div id="app"></div>
    <script src="https:[email protected]/dist/react.js"></script>
    <script src="https:[email protected]/dist/react-dom.js"></script>
    <script>
        // React is a global from the React library
        var div = React.DOM.div; // let's create a div!
        var h1 = React.DOM.h1; // let's create an h1!

        var App = div(null,
                      h1({id: "page-title"}, 'Hello World!'));

        // lets put this on the DOM
        ReactDOM.render(App, document.getElementById("app"));
    </script>
</body>
</html>

If we open this in the browser we should see "Hello World!". This may look quite strange, so let's talk more about what we did. div and h1 are actually functions provided to us by React.

The first parameter to each function is an object of attributes for the DOM element that we are creating. The names of most attributes are unchanged from what you would write in plain HTML. The one exception is the class attribute: since class is a reserved keyword in JavaScript, if you want to set the class of an element using the attribute object in React, you should use the className key. In this example, the div has no attributes, so we pass in null as the first argument. On the other hand, h1 has an id attribute.

The second argument to each function is the inner HTML of the element that we are creating. In this example, the div has an h1 tag inside of it, and the h1 tag has the text Hello World! inside of it.

Now we said that React is all about "components," but so far we have just been using existing HTML elements. Let's change things up by writing our first bona-fide React component.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>
    <div id="app"></div>
    <script src="https:[email protected]/dist/react.js"></script>
    <script src="https:[email protected]/dist/react-dom.js"></script>
    <script>

        // React is a global from the React library
        var div = React.DOM.div; // let's create a div!
        var h1 = React.DOM.h1; // let's create an h1!

        class MyComponent extends React.Component {
            render() {
               return div(
                        null,
                        h1(null, "My very first component!")
                    );
            }
        }

        var App = (
            div(null,
                h1({id: "page-title"}, 'Hello World!'),
                // now lets add our component!
                React.createElement(MyComponent, null)
            )
        );

        // lets put this on the DOM
        ReactDOM.render(App, document.getElementById("app"))
    </script>
</body>
</html>

Now let's see what that looks like! We just made up our own component and we can start using it anywhere!

Note that when we created MyComponent, we did it using ES2015 class syntax. (If you need a refresher on this syntax, check out the ES2015 Class Sytnax chapter of the Advanced JavaScript Part II course.) It used to be possible to create components without ES2015 using a method called React.createClass, but as of version 15 of React this method is deprecated and slated for removal in version 16. We'll add more ES2015 syntax to our React code over time, but if you're curious about using React without ES2015, you can head over to the docs to learn more.

It's cool that we've built our first custom component in React, but MyComponent is still fairly rigid. It will have the same structure and content no matter where we put it. It would be better if we could add some flexibility to it; for instance, it might be nice if we could modify the text inside of the component when it renders.

To achieve this goal, let's introduce a concept called props. We can think of these as "properties" for our components. Here's an example of what they look like:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>
    <div id="app"></div>
    <script src="https:[email protected]/dist/react.js"></script>
    <script src="https:[email protected]/dist/react-dom.js"></script>
    <script>

        // React is a global from the React library
        var div = React.DOM.div; // let's create a div!
        var h1 = React.DOM.h1; // let's create an h1!

        class MyComponent extends React.Component {
            render() {
               return div(
                        null,
                        h1(null, "My very first component!"),
                        h1(null, "Hello " + this.props.name)
                    );
            }
        }

        var App = (
            div(null,
                h1(null, 'Hello World!'),
                // now lets add our component!
                React.createElement(MyComponent, null),
                React.createElement(MyComponent, {name: "Elie"}),
                React.createElement(MyComponent, {name: "Tim"}),
                React.createElement(MyComponent, {name: "Matt"})
            )
        );

        // lets put this on the DOM
        ReactDOM.render(App, document.getElementById("app"));
    </script>
</body>
</html>

Notice that MyCompoennt now uses this.props.name to decide what text to render and when MyComponent is created using createElement, we are passing in an object with a key name that will set what this.props.name will be equal to. One important thing to note (which we will cover in more detail in the Props chapter) is that this.props.name is immutable. In other words, this.props.name will never change for the life of that component. We we talk more about why that is useful when we introduce props in more detail later.

We've done some pretty cool stuff here, but you might be thinking that this syntax is a bit strange. Fortunately, there is another way of using JavaScript to write HTML with a language called JSX. JSX might be a bit tricky to get used to at first, but it's the standard when writing React and can do some pretty incredible things once you get used to it. We'll dig into JSX in the next chapter.

Exercise

Complete the intro to React exercise.

When you're ready, move on to JSX and Babel

Continue