Quick Introduction to key React concepts

‚ú® 27 people thanked Hrishi Mittal for this tutorial.

ūüĎć Send Thanks
React Homepage - https://facebook.github.io/react/

The code for the examples in this video is available at the links below - 

Hello World - https://codepen.io/learnetto/pen/rWPVaG?editors=1010

Props - https://codepen.io/learnetto/pen/PbVqPY?editors=1010

State - https://codepen.io/learnetto/pen/XNObdV?editors=1010

In this video I'm going to do a quick introduction to ReactJS. 

We are going to look at the key concepts behind React, why it's a good idea to use React, and some example code to get a feel for what it looks like.

React is an open-source JavaScript library for building user interfaces.

It was created by Facebook and released back in 2013. All the code and the documentation is available at this website.

Since it was released three years ago, React has grown to be one of the most popular front-end libraries in use, both for web and mobile apps. 

The key concept behind React is the idea of replacing front-end view templates with simple, reusable components written in JavaScript. 

For example, in Rails, instead of writing all your UI code in erb or haml templates, you would create JavaScript components, which build up your app's UI. 

Let's look at an example. This is Google calendar:

Google calendar UI imagined as composed of nested components


Here, we could look at how, how we would build this in React.

Each of the coloured boxes can be considered as React components, and React has this idea of nesting components.

So the red box here could be a container component, which contains all of the other components inside the app. The blue box could be a component for the month, and the green one would be a component for each week, for each row of days in the week. And inside that is the purple component which is for specific  day, and then inside that, each appointment for that day.

Now notice the green component, for example, would be reusable, because the same component could be used for each week of the month. Similarly, the month component would be reusable because the same month component could be used for each month of the year. 

The day component is similarly reusable.

What's interesting about React is that instead of each of these bits of UI being a simple HTML or template markup code, it turns them into simple JavaScript objects. Each component is a JavaScript function which returns markup as its value. 

What this allows us to do is that, because it's JavaScript code - JavaScript functions essentially - it allows us to reason about the UI and reuse code in a much more efficient manner. This will be much clearer when we actually look at specific code examples, later in this lesson.

Now before we jump into looking at the code, let's quickly look at why React is a good idea. 

Why should you use React?

The four main reasons, I think, that React is such a  great idea and why it's become so popular:

  1. Easily maintainable
  2. Declarative
  3. Faster
  4. Cross-platform

1. React is easily maintainable. 

Now, we've all seen, as web projects grow in size, especially the front-end JavaScript code becomes very messy. You soon end up in a mess of spaghetti code  with all sorts of interactions and data and state manipulations strewn all over the place.

React allows us to replace the spaghetti code with well-structured and logical UI components.  Right from structuring the code files, down to how the code actually works, React allows code to be much more maintainable, especially when working in teams.

2. React code is declarative, as opposed to imperative. 

Instead of telling the computer how to do something, we just specify what we want. Instead of specifying every single step of how to handle user interaction - when a user clicks a button, what to update, which bit of the UI to change - we simply tell React what we would like for our data to do, and React automatically refreshes the UI and handles all the UI transitions. 

You  can think of it a bit like SQL, which is a declarative language, not imperative. You simply define your query in terms of what data you're looking for, and then the SQL database figures out the most efficient way to get that answer to you.

That's what React does for UIs. 

3. React allows us to build faster UIs

One of the main underlying concepts behind React is the idea of the Virtual DOM - a copy of the DOM.

React creates a virtual representation of the browser DOM and does all the operations on the virtual DOM instead of directly manipulating the DOM every time the data changes. 

Whenever the data changes, say, from the user action or from the server, React creates a new version of the Virtual DOM, and it then compares the old version of the virtual DOM to the new one, finds the differences between them, and only then makes the minimum amount of change that it needs to make to the actual DOM.

Making changes to the actual browser DOM is very expensive and slow.  By minimising those changes, React manages to make things a lot faster than us manually updating DOM elements, as we would typically do with something like jQuery. 

4. React allows us to write cross-platform code

Instead of write once and run everywhere, React community has adopted the concept of "Learn once, write anywhere". 

Once you learn how to write web UIs using React, you can use the same style of code, the same structure, to write native code for mobile apps.  There's very little difference in how they they work. 

Facebook has, in fact, found that for some of their apps they can share between 80 and 90 per cent of code between their Android and iOS apps. So this allows you to write a lot less code and achieve a lot more through it.

Especially for web developers looking to get into mobile development, this is one of the key features of React which makes it more attractive than other competing libraries and frameworks.


Now this is a lot of theory, and you may be feeling a bit overwhelmed with all these different ideas, and we've barely touched the surface of all the important concepts behind React. So let's look at some actual code to give you feel for what  React actually looks like.

So here we have some code, which displays a simple "Hello, world!" message on a web page:

<html>
  <body>
    <div id='app'></div>
  </body>
</html>

var Hello = React.createClass({
  render: function(){
    return (
      <div>Hello World!</div>
    )
  }
});

ReactDOM.render(<Hello />, document.getElementById('app'));

You can run this code on codepen.

All this code does is create a very basic React component, which is then used to simply display the words "Hello, world!" on a web page.

The HTML is very simple. We have one single div tag with an id app inside the body.

The React code renders "Hello world!" inside that div.

First we create our React component as a variable called Hello by calling React.createClass, which provides a render method, which in turn creates the actual markup for displaying  "Hello world!".

Then we call ReactDOM.render passing it two arguments - the component to be rendered and the place we want it to be rendered. In this case, we want to render the Hello component inside the div with id app.

Note that we use a React component as if it were an HTML tag. For example, we use the Hello component by enclosing it in angle brackets: <Hello />.

Remember, I mentioned earlier that, React creates components which are essentially functions which return markup.

Each React component must have a render function. That is what returns the actual UI markup. 

JSX

Our Hello component has just one function, the render function:

var Hello = React.createClass({
  render: function(){
    return (
      <div>Hello World!</div>
    )
  }
});

which returns this markup: 
<div>Hello World!</div>
 
Now, you might be wondering why there is  HTML inside JavaScript.

This is called JSX, one of the new things that React has introduced. JSX is basically a syntax extension for JavaScript.

It's a way to turn HTML markup into JavaScript objects.

It's not compulsory to use JSX with React but it is highly recommended and almost everyone uses it, because it makes using React a lot easier. 

It may feel a bit strange at first but you get used to it very quickly.

Initially JSX may seem just like another template language, but in fact, it comes with the full power of JavaScript. As you use and see more of its properties you'll realise that it's actually very powerful, much more powerful than a normal template language.

Props

Now since React components are functions, we can pass arguments to them. 

For example, in this our Hello component, instead of showing "Hello world", say we want to pass a value, a name of a person 'John', to this component. 

We can do that in React, using something called props. 

So let's change our code now to see how this would work. 

Let's change the ReactDOM.render call by passing a prop called name to Hello, with the value 'John':

ReactDOM.render(<Hello name='John' />, document.getElementById('app'));

And now let's change the returned markup in the render method in Hello to use this prop value:

 <div> Hello {this.props.name}!</div>

You can see the full code in this codepen.

Now, the web page displays "Hello John!" instead of "Hello World!".

If we change the value of name to "Mary", the page will show "Hello Mary!".

So props are simple way for passing data to components.

In our example here, name is an attribute whose value we are setting to "Mary", and then that is passed to the <Hello /> component, which accesses it through this.props.

Props are to components what arguments are to functions. 

They can be used inside, inside the JSX code, using curly braces {}. 

Anything inside curly braces in JSX is an expression, evaluates to an expression.

So for example here, if we write {2+2}, that will evaluate to 4. 

That's the use of curly braces, but in this case we are just using that to pass a prop value.

State

Next we're going to look at the concept of state. 

State is a way for components to maintain the internal state of app data. 

Any non-trivial app is gonna have some state, for example, even if you are just building a to do list app, you'll need to store the list items, whether they are completed or not, the order of the items, the date of the items, all of this data is the state of inside your app.

And React components can maintain their internal state data. 

It can be accessed via this.state just like we access this.props, and when a component's state data changes, the rendered markup is automatically refreshed by invoking render.

Now let's look at an example for state. You can run it on this codepen.

var Hello = React.createClass({
  getInitialState: function() {
    return {
      name: 'World'
    }
  },
  changeName: function(e) {
    this.setState({
      name: e.target.value
    })
  },
  render: function() {
    return (
      <div>
        <form>
          <input 
            onChange={this.changeName}
            value={this.state.name} />
        </form>
        <p> Hello {this.state.name}!</p>
      </div>
    )
  }
});

ReactDOM.render(<Hello />, document.getElementById('app'));

Now we've taken our "Hello World!" example. We've added a form text input field above the text "Hello World!".

And whatever the user types in the input field is displayed with "Hello".  So if you type "John", then it's reflected as "Hello John!". 

State

So let's look at how we would implement state in our example with the name prop.

Let's first add a form and an input field to the render method:

  render: function() {
    return (
      <div>
        <form>
          <input />
        </form>
        <p> Hello {this.props.name}!</p>
      </div>
    )
  }

Note that all the markup returned by the render method of a React component needs to be enclosed within a single element. Here we're enclosing everything inside a single div tag.

That's just a requirement of React, if you don't do that, then the component doesn't work.

Now we've added an input field. When the user types in the field that value should be displayed below with "Hello".

So first let's add a method called changeName to handle the onChange event for the field:

<input onChange={this.changeName} />

 And let's define changeName:

  changeName: function(e) {
    this.setState({
      name: e.target.value
    })
  }

Every time the field value changes, this function changeName is called, which calls this.setState, which is how you change state in React. This is known as an explicit mutation.

So we change value of name to e.target.value, where e is the onChange event and the target is the input field.

We also need to set the value of the input field to this.state.name.

<input onChange={this.changeName} value={this.state.name} />

And also use the value of name from the state instead of props to display next to "Hello":

<p> Hello {this.state.name}!</p>

We don't need to pass the name prop to Hello any more inside ReactDOM.render.

For this to work, we also need to initialise the state. 

So we need to write another function called getInitialState, which sets the state of the app when it first loads. Here we are setting the initial state value of name to 'World'.

getInitialState: function() {
  return {
    name: 'World'
  }
}

So that's what the page is going to initialise to, and then, when the user types in the input field, every time that field value changes, the onChange event triggers a call to this.changeName, which calls this.setState and sets the value of name in the state to the value of the input field.

Here's the full code and you can run it on this Codepen:

var Hello = React.createClass({
  getInitialState: function() {
    return {
      name: 'World'
    }
  },
  changeName: function(e) {
    this.setState({
      name: e.target.value
    })
  },
  render: function() {
    return (
      <div>
        <form>
          <input 
            onChange={this.changeName}
            value={this.state.name} />
        </form>
        <p> Hello {this.state.name}!</p>
      </div>
    )
  }
});

ReactDOM.render(<Hello />, document.getElementById('app'));

So this is a very simple, trivial example of how state works in React.

We're going to see more complex examples as we build something non-trivial in this course, but this is just to get a basic idea of how this works.

You can see a slightly more complex example of state on the React homepage:
A React timer

Here, this is an example of a timer which displays seconds elapsed, starting from zero on page load.

You'll notice that this code looks slightly different from the way we've written that in our example.

This is because these examples are using ECMAScript 6 (ES6), whereas we were using the previous version of JavaScript.

We will move on to using ES6, but just as an introduction, I wanted to show you something simple. 

So that covers some of the very basic concepts of React. 

Hopefully you got a feel for what is involved  in writing React code. 

There's a lot more to cover and we will as we move through the course, all in the context of using React within Rails. 

Some of the things we are going to look at is how to use external plugins and add-ons with React code, how to use Webpack, how to use ES6 instead of ES5 or previous versions of JavaScript.

We'll take a look at React router and also managing state with Redux.

Next we're going to see how to get started actually using React inside a Rails app.

Liked this tutorial? Get more like this in your inbox