Programming Tutorials

  • View all tutorials
  • Introduction to React
    React is a JavaScript library created by Facebook for easily creating user interfaces. Facebook's main reason for creating React was to solve the problem of building large applications where data changes over time. In this tutorial we'll cover how to include the React library in our code, and then we'll create a few simple components that reads data entered in by the user.

    What is JSX?

    Within code that uses React you may see tags that look similar to HTML tags, but they are used directly within JavaScript code. JSX is a JavaScript syntax extension that makes it a bit easier to create HTML tags and stacked components in large UI's. You'll be seeing JSX in place of vanilla JavaScript within React code below.

    Installing React

    To start using React only 3 scripts need to be included on your web page. The first is the actual React library, the second is for React's virtual DOM, and the third is the Babel transpiler which will convert the JSX code into JavaScript so the browser can understand our code. By including the Babel transpiler script, and placing our code within the text/babel script tags, our JSX code will automatically be converted in the browser when we open the file.
    <!DOCTYPE html>
    <html>
    <head> 
      <meta charset="utf-8" />
      <title> Testing React </title>    
      <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.0.2/react.min.js"></script>  
      <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.0.2/react-dom.min.js"></script>  
      <script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.23/browser.min.js"></script>        
    </head>
    <body>
      <div id="main"></div>
      <script type="text/babel">
        // React code goes here...
      </script>
    </body>  
    </html>
    

    Create a Counter component

    We'll start off with a simple example by creating a timer. This will introduce you to several React properties and functions such as state and render, and how to insert React components into the DOM. This example is part of the starter kit which provides several examples, but we'll be modifying a few things in the code. The goal of using React is to make it easy to create, update, and modify different UI components without our code turning into spaghetti code. It allows us to create components where everything they need to function properly is contained within a small module. We'll call our component Counter, and then we'll setup our component to render within the main div we created.
    // create a React component
    var Counter = React.createClass({
      // methods go here...
    });
    
    // render a React component in the DOM
    // first parameter is the component
    // second parameter is the DOM element we're inserting it into
    ReactDOM.render(
      <Counter />,
      document.getElementById('main')
    );
    
    Now that we have the starter code setup, we can start creating a counter. We'll create a button that will update a variable, and then we want the DOM to update and display the new number as well. With vanilla JavaScript (no libraries or frameworks), to do this you would have to have create some sort of function that listens for changes to a variable and then updates the DOM with the new variables. With React, modifying data and updating the DOM becomes very easy, as you'll see it requires no extra work. The code below creates a few HTML elements that we will insert into the DOM via the required render function. Then we create two functions that will update the counter and reset the counter.
    // create a React component
    var Counter = React.createClass({
    
      // this function will update our counter
      updateCounter: function() { },
    
      // reset the counter variable
      resetCounter: function() { },
    
      // this render function returns the elements that will be
      // inserted into the DOM with the corresponding data
      render: function() {
        return (
          <div>
            <button onClick={this.updateCounter}> Click me! </button>
            <p> Number of clicks: </p>
            <p> The threshold is set to: </p>
            <button onClick={this.resetCounter}> Reset </button>
          </div>
        );
      }
    
    });
    
    // render a React component in the DOM
    // first parameter is the component
    // second parameter is the DOM element we're inserting it into
    ReactDOM.render(
      <Counter />,
      document.getElementById('main')
    );
    
    With the code above, we haven't created any interaction or events yet, but we have created some HTML elements that are inserted into the DOM. You can see the output of the code here. You should see the following HTML output:

    React state

    One of the great things about React is that we don't have to worry about updating our UI when some data changes. We can simply change the data, and React's virtual DOM will figure out what to change and how to do it efficiently. All we have to do is modify the component's state. We'll add a method called getInitialState which React calls when the component is first created to setup some variables. For this component we need two variables, one for the counter and another to act as a threshold.
    // create a React component
    var Counter = React.createClass({
     
      // "this.props" object comes from the component in the ReactDOM.render function
      getInitialState: function() {
        return { 
          count: 0,
          threshold: this.props.threshold
        };
      },
    
      // this function will update our counter
      updateCounter: function() { },
    
      // reset the counter variable
      resetCounter: function() { },
    
      // this render function returns the elements that will be
      // inserted into the DOM with the corresponding data
      render: function() {
        return (
          <div>
            <button onClick={this.updateCounter}> Click me! </button>
            <p> Number of clicks: {this.state.count} </p>
            <p> The threshold is set to: {this.state.threshold}</p>
            <button onClick={this.resetCounter}> Reset </button>
          </div>
        );
      }
    
    });
    
    // render a React component in the DOM
    // first parameter is the component
    // second parameter is the DOM element we're inserting it into
    ReactDOM.render(
      <Counter threshold={5} />,
      document.getElementById('main')
    );
    
    If you run the above code, you can see that the DOM now gets updated with the values 0 and 5, without us needing to explicitly tell the DOM to insert those values. The data values are available under the object this.state._NAME_. The component updates the state of the data whenever it changes or when it's first created. Now we just need to create the update and reset functions to update the data. You can see the above code in action here. We update the state of our component using the setState function. We'll update the empty functions below, and we'll get a working Counter component that notifies you when you reach the threshold each time, and allows you to reset everything back to the starting point.
    // create a React component
    var Counter = React.createClass({
     
      // "this.props" object comes from the component in the ReactDOM.render function
      getInitialState: function() {
        return { 
          count: 0,
          threshold: this.props.threshold
        };
      },
    
      // this function will update our counter
      updateCounter: function() { 
        this.setState({ count: this.state.count + 1 });
        if (this.state.count === this.state.threshold) {
          alert('You passed the threshold!');
          this.setState({ threshold: this.state.threshold + 5 });
        }
      },
    
      // reset the counter variable
      resetCounter: function() { 
        this.setState(this.getInitialState());
      },
    
      // this render function returns the elements that will be
      // inserted into the DOM with the corresponding data
      render: function() {
        return (
          <div>
            <button onClick={this.updateCounter}> Click me! </button>
            <p> Number of clicks: {this.state.count} </p>
            <p> The threshold is set to: {this.state.threshold}</p>
            <button onClick={this.resetCounter}> Reset </button>
          </div>
        );
      }
    
    });
    
    // render a React component in the DOM
    // first parameter is the component
    // second parameter is the DOM element we're inserting it into
    ReactDOM.render(
      <Counter threshold={5} />,
      document.getElementById('main')
    );
    
    You can see the final working component code here.

    Conclusion

    The beauty of the above component is that all we have to manage is what the data is initially, and how it's updated. The DOM is updated automatically for us once the data, or state, changes. We can also pass in certain properties via the props object into the component before it gets rendered.
    mrdaniel wrote this tutorial on 5/13/16 | javascript, react
    Comments
    Log in to submit a comment.