Home » JavaScript » React.js » ReactJS Getting Started Example

About Jean Vester

Jean Vester
Jean-Jay Vester graduated from the Cape Peninsula University of Technology, Cape Town, in 2001 and has spent most of his career developing Java backend systems for small to large sized companies both sides of the equator. He has an abundance of experience and knowledge in many varied Java frameworks and has also acquired some systems knowledge along the way. Recently he has started developing his JavaScript skill set specifically targeting Angularjs and also bridged that skill to the backend with Nodejs.

ReactJS Getting Started Example

In this article we will start our adventures in React. We will cover the set up of our local development environment, the various ancillary technologies needed to make our React application work and how a React application is composed.

We will finally pull everything together in a simple web application which we can run locally in our browser.

Knowledge of javascript, particularly ES6 is expected, although the example is superficial enough for most people with only an introduction to javascript to be able to follow along quite easily.

1. Introduction

React, also called reactjs, not be confused with react-native, is a component based javascript library for building user interfaces and it was created by an engineer, Jordan Walke, at Facebook.

It is extremely popular and has positioned itself not only as a leader in web view libraries but also as an implementation choice for creating native applications for mobile.

It carries an MIT license and the source code can be viewed here.

2. Technologies Used

The example code in this article was built and run using:

    • Javascript ES6
    • Nodejs v6.13.0
    • Npm v3.10.10
    • Create React App command line tool v1.5.1
    • Visual Studio Code v1.20.1
    • Ubuntu 16.04
    • Google Chrome v64.0.3282.167 (Official Build) (64-bit)

3. Setup

The following software packages need to be installed to follow along in this article.

3.1. Nodejs

Nodejs is a Javascript run time for developing and running Javascript applications without a browser. It is typically used for server side web application development and will be used in this article to serve our web application in the browser.

Nodejs can be obtained and installed from here. We can confirm successful installation on the command line.

Confirming Nodejs

jean-jay@jeanjay-SATELLITE-L750D:~$ nodejs --version
v6.13.0

Your version might differ as I have had installed for some time.

3.2. Npm

Npm is the package manager for Javascript applications and we will be using it in this article. Npm is installed automatically when installing Nodejs. We can confirm successful installation on the command line.

Confirming Npm

jean-jay@jeanjay-SATELLITE-L750D:~$ npm --version
3.10.10

Your version might differ as I have had installed for some time.

3.3. Visual Studio Code

Visual Studio Code can be installed from here. It is the editor I will be using for this article, but it is not essential that you use it. Any text editor will do.

3.4. Create React App

Create-react-app is a command line tool that streamlines the development of React applications using a standard set of conventions and dependencies instead of explicit configuration. It can be installed by issuing the following command line instruction sudo npm install -g create-react-app

In this step we demonstrate how to create a React application using the command line tool we previously installed via npm.

Even though this step is not necessary as the sample application is downloaded, this serves as reference for you when you decide to do your own.

Creating a React application

sudo create-react-app reactjs-getting-started
[sudo] password for jean-jay: 

Creating a new React app in /home/jean-jay/Documents/github-projects/codegeeks/reactjs-getting-started.

Installing packages. This might take a couple of minutes.
Installing react, react-dom, and react-scripts...


> uglifyjs-webpack-plugin@0.4.6 postinstall /home/jean-jay/Documents/github-projects/codegeeks/reactjs-getting-started/node_modules/uglifyjs-webpack-plugin
> node lib/post_install.js

reactjs-getting-started@0.1.0 /home/jean-jay/Documents/github-projects/codegeeks/reactjs-getting-started
...
...
Success! Created reactjs-getting-started at /home/jean-jay/Documents/github-projects/codegeeks/reactjs-getting-started
Inside that directory, you can run several commands:

  npm start
    Starts the development server.

  npm run build
    Bundles the app into static files for production.

  npm test
    Starts the test runner.

  npm run eject
    Removes this tool and copies build dependencies, configuration files
    and scripts into the app directory. If you do this, you can’t go back!

We suggest that you begin by typing:

  cd reactjs-getting-started
  npm start

Happy hacking!

Once complete you can simply run npm start and this command will start a local nodejs server which will serve our  React application. Your default browser will launch and load the following page:

Start React Application screen

4. ES and Babel

In this article we will be using ES6 (ecma script 6) features when coding the example. Because ES6 is fairly new and some people still run browsers which do not support ES6 features it is necessary to compile our feature rich, ES6, Javascript into platform browser compliant software. To do this we use the Babel compiler.

If you are not familiar with ES6, don’t fear, you can make use of the Babel repl to see what the ES6 features get compiled into to be able to run in older browsers. But generally the example code is superficial enough to be able to wing it.

5. Why React?

The web development space is changing constantly and it can be quite difficult knowing where to start or what to learn. For most of us time is a scarce commodity, that’s why choosing the right thing to learn or focus on is especially important.

This begs the question, why React? What makes it special among the plethora of web development frameworks out there. I will try to distill the noise into a set of reasons as to why you should consider React.

  • It is simple in architecture and implementation. React has a simple, well defined life cycle with a modular approach to page component design. Because it has a heavy focus on “just” Javascript it makes it easier to learn. Other frameworks require adoption of a new language making the barrier to entry far higher.
  • Should you be wanting to explore mobile development, React offers a fluent development experience by bringing the same experience for web to mobile, thus also reducing the learning curve.
  • React applications lend themselves to test-ability through their architecture and utilities that ship with the library.
  • React applications are very performant. Leveraging a virtual DOM and targeting SPA designs user experience is a core focus.
  • React is focused on the “view” part of web applications and can be combined, even, with other web frameworks like Angular.
  • React is open source, ubiquitous and actively maintained by the community, including big companies like Facebook and Instagram.

6. Components

At the heart of it all are components, it’s what allows us to make our application dynamic, modular and testable.

A component could be anything on our page, it could be a menu component, a header component, a calendar component, a date picker component etc.

In React we distinguish between two general types of components, statefull and stateless. Statefull as the name implies manages state whereas a stateless component does not.

The purpose of a component is to accept some input through a variable called props and then render / update a part of the DOM as a result of executing the component.

A component can indicate to React when it should call the render() method of the component by calling setState(). This will indicate to React that some state has changed and therefore the DOM should be updated.

7. JSX

JSX is a preprocessor step that adds syntactic sugar to your Javascript code. It allows us to define our render()result in “near” HTML code.

Even without any experience in using JSX, the code looks familiar enough for people with only HTML experience to be able to follow the code without too much of a problem.

Based on our JSX code, the preprocessor step in our compilation process will synthesize the necessary Javascript code which will result in our JSX code being properly translated into the HTML equivalent.

JSX

<div className="Test">
	<MyCustomComponent/>
	<p>Hello world!</p>
</div>

… is “roughly” compiled into

Javascript

React.createElement('div',{class : 'Test'},
                    React.createElement('MyCustomComponent', null,
                                        'p', null, 'Hello world!'));
  • Each element (custom or HTML) is compiled into a React.createElement(...) call where the first argument denotes the type of element, the second argument denotes the css configurations and the third element represents any children of the element. Thus subsequent React.createElment(...)calls for hierarchical structures or a string representing inner HTML.

8. Putting it together

Our application is simple. At the root we have an index.js which will register a service worker to enable a more progressive application but will also append our application content to the DOM at thediv element with id root.

Further to that we have three custom components Todo CentredItemInputand ItemDisplay.

They are responsible for encapsulating our application (Todo) , accepting input (CentredItemInput) and displaying our items (ItemDisplay).

Todo root component

import React, { Component } from 'react';
import './Todo.css';
import CenteredItemInput from './centered-item-input/CenteredItemInput';
import ItemDisplay from './item-display/ItemDisplay';

// statefull component: will encapsulate the todoItems and perform actions on said state
class Todo extends Component {

  // our todo items represented as a state object with an array of todo items
  state = {
    todoItems: []
  };

  // adds the given todoItem to our list of todo items
  // using arrow function (ES6) allows us to use the 'this' reference for correct scope ie: this object
  addTodoItem = (todoItem) => {
    this.state.todoItems.push(todoItem);

    // this is required when updating any managed state - this way React
    // can be notified when a state change happens and call the render() method
    // of this component.
    this.setState({
      todoItems: this.state.todoItems
    });
  };

  // delete the todo item indexed by the given idx
  // using arrow function (ES6) allows us to use the 'this' reference for correct scope ie: this object
  deleteTodoItem = (idx) => {
    let todoItems = this.state.todoItems;
    todoItems.splice(idx, 1);

    // this is required when updating any managed state - this way React
    // can be notified when a state change happens and call the render() method
    // of this component.
    this.setState({
      todoItems: todoItems
    });
  };

  // called by React to render this part of the DOM, our JSX snippet.
  // pass this.addTodoItem function to CenteredItemInput Component via the addItem attribute
  // pass this.state.todoItems array to the ItemDisplay Component via the items attribute
  // pass this.deleteTodoItem function to the ItemDisplay component via the deleteItem attribute
  render() {
    return (
      <div className="Todo">
        <header className="Todo-header">
          <h1 className="Todo">Todo list</h1>
        </header>
        <CenteredItemInput addItem={this.addTodoItem} />
        <ItemDisplay items={this.state.todoItems} deleteItem={this.deleteTodoItem} />
      </div>
    );
  };
};

// export this class as the default export so that when importing from this file we will by default
// get this class.
export default Todo;
  • In this class we define our root component for the application.

CenteredItemInput component

import React, { Component } from 'react';
import './CenteredItemInput.css';

// our text input stateful component
class CenteredItemInput extends Component {

  // the state we are managing
  state = {
    input: ''
  };

  // clears our state / input box by calling the 'setState' method
  // this will indicate to React that the state has changed an trigger a call to render()
  // for this component
  clearInput = () => {
    this.setState({
      input: ''
    });
  };

  // sets our state / input box by calling the 'setState' method
  // the setTodoItemEvent encapsulates an onChange event triggered by key input in our text field
  // this will indicate to React that the state has changed an trigger a call to render()
  // for this component
  setInput = (setTodoItemEvent) => {
    let updated = setTodoItemEvent.target.value;
    this.setState({
      input: updated
    });
  };

  // will take the value in our managed state for this component
  // and call the function on the parent component (Todo) responsile for adding the item
  // clearInput is called to clear the input field once this is done
  addItem = () => {
    if (this.state.input === '') {
      alert('Requires input');
    } else {
      this.props.addItem(this.state.input);
      this.clearInput();
    }
  };

  // this components contribution to the DOM, the JSX snippet
  render() {
    return (
      <div className="Centered-item-input">
        <div className="Centered-item-input-flex-pad" />

        <div className="Centered-item-input-item">
          <form className="form-inline">
            <div className="form-group mx-sm-3 mb-2">
              <input type="text" id="input-desc" className="form-control" size="50" placeholder="Add todo item here" onChange={this.setInput} value={this.state.input} />
            </div>
            <button type="button" onClick={this.addItem} className="btn btn-primary mb-2">Add</button>
          </form>
        </div>

        <div className="Centered-item-input-flex-pad" />
      </div>
    );
  };
}

// export the class CenteredIntemInput as the default export for this class
export default CenteredItemInput;
  • In this component we capture a new todo item

ItemDisplay component

import React from 'react';
import './ItemDisplay.css';

// a stateless component implemented as an arrow function that receives a props object holding
// the state and or functions passed to this component.
const ItemDisplay = (props) => {
    let response = (props.items.map((todoItem, idx) => {
        return <div key={idx} className="Item-display-row">
            <p>
                <button type="button" className="btn btn-danger mb-2" title="Delete item" onClick={() => props.deleteItem(idx)}>
                    <i className="fa fa-close"></i>
                </button>
                <span className="Item-display-row-text">{todoItem}</span>
            </p>
        </div>
    }));

    return (<div className="Item-display">{response}</div>);
};

export default ItemDisplay;
  • In this component we display the items we have added and are able to remove items

9. Running the app

To use the application the following steps need to be done:

  • Download the example project and extract it somewhere on your system.
  • Navigate to the location where you extracted the downloaded contents and execute the following: npm install && npm start

The dependencies will be downloaded from Npm and the application will be started. A browser window will be opened when ready.

Start the application

At this point you can start typing in items (“todo items”) and adding them to your list. The application is very simple, no real validation exists and the list is unbounded, but it does showcase some features of React and how to get started with it.

10. Summary

In this article we introduced ourselves to React, understood it’s origins, it’s applicability, how it functions (briefly) and how we can use it and other required ancillary technologies to build a simple user interface.

11. Download the Source Code

This was a ReactJS Getting Started Example

Download
You can download the full source code of this example here ReactJS Getting Started Example
(0 rating, 0 votes)
You need to be a registered member to rate this.
Start the discussion Views Tweet it!
Do you want to know how to develop your skillset to become a Web Rockstar?
Subscribe to our newsletter to start Rocking right now!
To get you started we give you our best selling eBooks for FREE!
1. Building web apps with Node.js
2. HTML5 Programming Cookbook
3. CSS Programming Cookbook
4. AngularJS Programming Cookbook
5. jQuery Programming Cookbook
6. Bootstrap Programming Cookbook
and many more ....
I agree to the Terms and Privacy Policy

Leave a Reply

avatar

This site uses Akismet to reduce spam. Learn how your comment data is processed.

  Subscribe  
Notify of