Learning Management Platform for Written Tutorial Series.

React Components

React Components

Introduction

This tutorial is the fourth part of a series to get up and running with ReactJS, here we will learn how to use React components, the building blocks of React, React is a library developed by Facebook to simplify the creation of complex user interfaces. React components are re-usable design elements that speed up development and simplify the debugging process.

Topics to be covered

We will cover the following topics in this tutorial

  • Tutorial pre-requisites
  • React Components
  • React Component Properties
  • React Events
  • React Component State
  • Nesting Components

Tutorial pre-requisites

For you to complete this tutorial successfully, you will need to at least know / have the following.

  • Web server – you can still run React code without a web server but then you will not be able to use extensions such as react-detector as they require the http protocol.
  • You should be familiar with HTML, CSS and JavaScript basics.
  • You should be familiar with the basics of ReactJS. If you are not familiar with the basics, read the previous tutorials.
  • You should have text editor or Integrated Development (IDE) that supports HTML, CSS and JavaScript
  • An update to date browser that has JavaScript enabled. Google chrome is highly recommended since we will be using Google Chrome extensions to debug the code. You can also use other browsers such as Firefox and download the appropriate React Developer Add-ons.
  • You have a command line tool or terminal and you know the basics

React Components

React components are the building blocks of the user interface, they are the Lego pieces that you put together to create the front end of the web application, these components are reusable. You can try it out in the previous example by updating the ReactDOM.render function with this line.

ReactDOM.render(<div><Hello/><Hello/><Hello/><Hello/></div>, document.getElementById('react-target'));

HERE, - ReactDOM.render(<div><Hello/><Hello/><Hello/><Hello/></div>, document.getElementById('react-target')); nests the Hello component four (4) times inside a div element.

The complete code should be as follows

<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <title>React Components</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
</head>

<body>
    <div class="container">
        <h1>React Components Example</h1>
        <div/>
        <div id="react-target">
            <p>
                React should start working in a few milli seconds
            </p>
            <p>
                If you can see this, React is not working right.
            </p>
        </div>

        <script src="https://fb.me/react-0.14.6.js"></script>
        <script src="https://fb.me/react-dom-0.14.6.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.24/browser.min.js"></script>
        <script type="text/babel">

            var Hello = React.createClass({ render() { return (
            <div>
                <h1>Hello from Kode</h1>
                <p>Maybe you prefer a hello from Adele</p>
            </div>
            ) } }); ReactDOM.render(
            <div>
                <Hello/>
                <Hello/>
                <Hello/>
                <Hello/>
            </div>, document.getElementById('react-target'));
        </script>

</body>
</html>

The browser output will be as follows

React Components

As you will notice we have reused the Hello component 4 times, you can see that in the browser, we didn't need to retype the HTML elements. This is a very powerful code reuse.

PLEASE NOTE we enclosed the 4 Hello components with a div tag, The reason for that is the React will only output one element as child to target element, it doesn't render siblings, this is a common bug, React has very clear error messages in case you forget this.

React Component Properties

When we used the Hello component multiple time, all the 4 component were exactly the same, we need a way to be able to customize a component depending on our needs, here is where properties come in play, React components can accept properties when they are created. Replace the React application script with this:

<script type="text/babel">
var Hello = React.createClass({
render() {
    return (
        <div>
        <h1>{this.props.message}</h1>
        </div>
        )
      }
});

ReactDOM.render(<div>
<Hello message="Hello from one"/>
<Hello message="Hey from me"/>
<Hello message="Howdy from there"/>
<Hello message="Greetings Human"/>
</div>, document.getElementById('react-target'));
</script>

HERE,

  • <h1>{this.props.message}</h1> this.props.message is used to access the property message and output its value within <h1> tags. Please notice the use of curly braces when we need to write JavaScript syntax inside out JSX syntax.
  • <Hello message="Hello from one"/> the attribute message=”x” creates a property called message, this property becomes available in the component via this.props. we were able to modify the message property when creating each individual instance of the Hello component.

When you run this, you will notice the personalized messages in the browser

React Component Properties

Imagine you have a long list of book items that you need to output on your website, you can create a single component with properties like: author, title, publisher, date, price, etc. and reuse it to display a list of authors.

I hope you are starting to see the strength of React even with these very simple examples.

Let’s now look at how to access the children of the properties. Anything that comes between two tags are called children.

Now replace the JSX code with the following script:

<script type="text/babel">
var Hello = React.createClass({
    render() {
        return (
            <div>
            <h1>{this.props.message}</h1>
            <p>{this.props.children}</p>
            </div>
        )
      }
    });

ReactDOM.render(<div>
<Hello message="Hello from one">right back at you</Hello>
<Hello message="Hey from me">who is me</Hello>
<Hello message="Howdy from there">I am not that far away</Hello>
<Hello message="Greetings Human">Greetings computer</Hello>
</div>, document.getElementById('react-target'));
</script>

HERE,

  • <Hello message="x">… </Hello> We have modified the component to have an opening tag and a closing tag with some text in between, anything that comes between two tags are called children, we also have access to the children in the component as a property
  • <p>{this.props.children}</p> is used to access anything that is between the opening and closing tags of the React Component.

Save the changes and reload the page in the browser.

You will get the following results

React Component Child Property

React Events

React uses what is called synthetic event handlers, which is basically wrappers around browser native handlers, this approach makes React very good in all browsers, as you don't need to worry about browser specific events.

Replace the React application script with this:

<script type="text/babel">
var Hello = React.createClass({
    handleClick(){
        alert(this.props.children);
    },
    render() {
        return (
            <div>
            <h1 onClick={this.handleClick}>{this.props.message}</h1>
            </div>
          )
      }
});

ReactDOM.render(<div>
<Hello message="Hello from one">right back at you</Hello>
<Hello message="Hey from me">who is me</Hello>
<Hello message="Howdy from there">I am not that far away</Hello>
<Hello message="Greetings Human">Greetings computer</Hello>
</div>, document.getElementById('react-target'));
</script>

HERE,

  • { handleClick(){ alert(this.props.children); } this is the function that is called when the onClick event is raised.
  • <h1 onClick={this.handleClick}>{this.props.message}</h1> Here we have added an onClick event on the h1 tag, this event will call the function that we created to handle this event which is handleClick function, The function will call an alert with the custom child of the clicked Hello component instance.

Try it out in your browser and trying clicking on the messages, you will see a box pop-up with the reply, very cool!!!

ReactJS Events

Here I have click on (Greetings Human) then the React application replied with the alert message.

React Component State

State is a very important concept in React, as we have seen how properties are passed down to the component, state is the internal "state" of the component, hmmm state within a component changes to specific events, however properties do not, an example will show what I mean

Replace the React application script with this:

<script type="text/babel">
var Hello = React.createClass({
    getInitialState(){
        return {color: 'red'}
    },
    handleClick(){
        this.setState({color:'blue'});
    },
    render() {
        return (
            <div>
            <h1 style={{color: this.state.color}} onClick={this.handleClick}>{this.props.message}</h1>
            <p>{this.props.children}</p>
            </div>
        )
    }
});

ReactDOM.render(<div>
<Hello message="Hello from one">right back at you</Hello>
<Hello message="Hey from me">who is me</Hello>
<Hello message="Howdy from there">I am not that far away</Hello>
<Hello message="Greetings Human">Greetings computer</Hello>
</div>, document.getElementById('react-target'));
</script>

HERE,

  • getInitialState() This function will create a state for color and will set it to red, in the render function you can see that we are using the color state to modify the style of the h1 tag, so when we first render to the browser, all messages will have the red color.
  • handleClick(){ this.setState({color:'blue'}); } function that will update our color state to blue. It is invoked by the click event.
  • this.setState(…) this function is built in React and you should always use it to modify the state, NEVER attempt to change a state variable directly, because using setState will let React know that something has changed and that will trigger a re-render of the DOM

Go ahead and try this in the browser, try clicking on the messages, you should see that they will change their color from red to blue.

React State

In the Developer tools you are able to see the state of the highlighted Hello component (second Hello) the color is the initial red.

Nesting React Components

One of the great thing about React is the ability to nest components inside each other, when working with React, you should think of your application as a bunch of nested rectangles, one inside of the other, your most outer component will be the main component and it will contain all other components, this is the React way of thinking, this approach allows us to organize our concerns and ease the flow of data.

The enclosing component is called a parent component, the enclosed component is called a child component, the parent component can pass properties to its children. Replace the React application script with this:

<script type="text/babel">
var GreetBook = React.createClass({
    render(){
        return(
            <div>
            <Hello message="Hello from one"/>
            <Hello message="Hey from me"/>
            <Hello message="Howdy from there"/>
            <Hello message="Greetings Human"/>
            </div>
        )
     }
});

var Hello = React.createClass({
    getInitialState(){
        return {color: 'red'}
    },
    handleClick(){
        this.setState({color:'blue'});
    },
    render() {
        return (
            <div>
            <h1 style={{color: this.state.color}} onClick={this.handleClick}>{this.props.message}</h1>
            </div>
        )
      }
});

ReactDOM.render(<GreetBook/>, document.getElementById('react-target'));
</script>

Here we created a new component called GreetBook, this component is the parent of all the Hello components, the Hello component are call child components, if you check this in the browser you wouldn't know that there is a parent component, until you check the developer tools, this approach makes the code more organized.

As you can see here in the Developer Tools, we have a parent element called GreetBook which is holding the Hello elements as children.

Now let's assume that the messages are coming from a server and we will simulate that with an array variable that will hold the messages, we can further reduce the code in the GreetBook component by utilizing a JavaScript map function on the messages array :

<script type="text/babel">
var messages = [
      "Hello from one",
      "Hey from me",
      "Howdy from there",
      "Greetings Human"
];

var GreetBook = React.createClass({
    render(){
        var hello = messages.map(function(item){
            return<Hello message={item}/>
        })
        return(
            <div>
                {hello}
            </div>
        )
    }
});

var Hello = React.createClass({
    getInitialState(){
        return {color: 'red'}
    },
    handleClick(){
        this.setState({color:'blue'});
    },
    render() {
        return (
            <div>
                <h1 style={{color: this.state.color}} onClick={this.handleClick}>{this.props.message}</h1>
            </div>
        )
    }
});

ReactDOM.render(<GreetBook/>, document.getElementById('react-target'));
</script>

As you can see we only wrote the Hello component once and managed to get all instances of the messages, this would work even if the array had thousands of items, NEAT. In the browser you should see no change from last edit, it is only the way we are writing our code that changed, and we have made it DRY (Don't Repeat Yourself).

Summary

React Components are reusable components used to speed up developing user interfaces. React components have support for properties, events, and states.

What’s next?

In the next tutorial, we will introduce you to ReactJS Debugging. We will look at the available debugging tools and how you can use them.

If you found this tutorial useful, support us by using the social media buttons to like and share the tutorial. If you didn’t find it useful, please use the comments section below to let us know how we can do better next time.

Each week, a new ReactJS tutorial is added to our collection. Subscribe to our newsletter, like our Facebook fan page or follow us on Twitter to get free updates when the collection is updated.

Tutorial History

Tutorial version 1: Date Published 2016-02-02


...