Learn React.js for Beginners

Learn React.js for Beginners

A quick introduction to the popular JavaScript library. This tutorial will give you a basic understanding of React.js by building a verysimple application.

Once you’ve read this article, you can check out our free React course on Scrimba, where you’ll learn the library through 48 interactive screencasts.

Now let’s get started!


The setup

When getting started with React, you should use the simplest setup possible: an HTML file which imports the React and the ReactDOM libraries using script tags, like this:

<html>
<head>
<script src="https://unpkg.com/[email protected]/dist/react.min.js"> </script><script src="https://unpkg.com/[email protected]/dist/react-dom.min.js">
</script>
<script src="https://unpkg.com/[email protected]/babel.min.js"></script>
</head>
<body>
    <div id="root"></div>
    <script type="text/babel">

/* 
ADD REACT CODE HERE 
*/

&lt;/script&gt;

</body> </html>

We’ve also imported Babel, as React uses something called JSX to write markup. We’ll need to transform this JSX into plain JavaScript, so that the browser can understand it.

There are more two things I want you to notice:

  1. The <div> with the id of #root. This is the entry point for our app. This is where our entire app will live.
  2. The <script type="text/babel"> tag in the body. This is where we’ll write our React.js code.

If you want to experiment with the code, check out this Scrimba playground.


Components

Everything in React is a component, and these usually take the form of JavaScript classes. You create a component by extending upon the React-Component class. Let’s create a component called Hello.

class Hello extends React.Component {
    render() {
        return <h1>Hello world!</h1>;
    }
}

You then define the methods for the component. In our example, we only have one method, and it’s called render().

Inside render() you’ll return a description of what you want React to draw on the page. In the case above, we simply want it to display an h1 tag with the text Hello world! inside it.

To get our tiny application to render on the screen we also have to use ReactDOM.render():

ReactDOM.render(
    <Hello />, 
    document.getElementById("root")
);

So this is where we connect our Hello component with the entry point for the app (<div id="root"></div>). It results in the following:

The HTML’ish syntax we just looked at (<h1> and <Hello/>) is the JSX code I mentioned earlier. It’s not actually HTML, though what you write there does end up as HTML tags in the DOM.

The next step is to get our app to handle data.


Handling data

There are two types of data in React: props and state. The difference between the two is a bit tricky to understand in the beginning, so don’t worry if you find it a bit confusing. It’ll become easier once you start working with them.

The key difference is that state is private and can be changed from within the component itself. Props are external, and not controlled by the component itself. It’s passed down from components higher up the hierarchy, who also control the data.

A component can change its internal state directly. It can not change its props directly.

Let’s take a closer look at props first.


Props

Our Hello component is very static, and it renders out the same message regardless. A big part of React is reusability, meaning the ability to write a component once, and then reuse it in different use cases — for example, to display different messages.

To achieve this type of reusability, we’ll add props. This is how you pass props to a component (highlighted in bold):

ReactDOM.render(
    <Hello message="my friend" />, 
    document.getElementById("root")
);

This prop is called message and has the value “my friend”. We can access this prop inside the Hello component by referencing this.props.message, like this:

class Hello extends React.Component {
    render() {
        return <h1>Hello {this.props.message}!</h1>;
    }
}

As a result, this is rendered on the screen:

The reason we’re writing {this.props.message} with curly braces is because we need to tell the JSX that we want to add a JavaScript expression. This is called escaping.

So now we have a reusable component which can render whatever message we want on the page. Woohoo!

However, what if we want the component to be able to change its own data? Then we have to use state instead!


State

The other way of storing data in React is in the component’s state. And unlike props — which can’t be changed directly by the component — the state can.

So if you want the data in your app to change — for example based on user interactions — it must be stored in a component’s state somewhere in the app.


Initializing state

To initialize the state, simply set this.statein the constructor() method of the class. Our state is an object which in our case only has one key called message.

class Hello extends React.Component {

constructor(){
    super();
    this.state = {
        message: "my friend (from state)!"
    };
}

render() {
    return &lt;h1&gt;Hello {this.state.message}!&lt;/h1&gt;;
}

}

Before we set the state, we have to call super() in the constructor. This is because this is uninitialized before super() has been called.


Changing the state

To modify the state, simply call this.setState(), passing in the new state object as the argument. We’ll do this inside a method which we’ll call updateMessage.

class Hello extends React.Component {

constructor(){
    super();
    this.state = {
        message: "my friend (from state)!"
    };
    this.updateMessage = this.updateMessage.bind(this);

}

updateMessage() {
    this.setState({
        message: "my friend (from changed state)!"
    });
}    

render() {
    return &lt;h1&gt;Hello {this.state.message}!&lt;/h1&gt;;
}

}

Note: To make this work, we also had to bind the this keyword to the updateMessage method. Otherwise we couldn’t have accessed this in the method.

The next step is to create a button to click on, so that we can trigger the updateMessage() method.

So let’s add a button to the render() method:

render() {
  return (
     <div>
       <h1>Hello {this.state.message}!</h1>
       <button onClick={this.updateMessage}>Click me!</button>
     </div>
) }

Here, we’re hooking an event listener onto the button, listening for the onClick event. When this is triggered, we call the updateMessage method.

Here’s the entire component:

class Hello extends React.Component {

constructor(){
    super();
    this.state = {
        message: "my friend (from state)!"
    };
    this.updateMessage = this.updateMessage.bind(this);
}

updateMessage() {
    this.setState({
        message: "my friend (from changed state)!"
    });
}

render() {
     return (
       &lt;div&gt;
         &lt;h1&gt;Hello {this.state.message}!&lt;/h1&gt;
         &lt;button onClick={this.updateMessage}&gt;Click me!&lt;/button&gt;
       &lt;/div&gt;   
    )
}

}

The updateMessage method then calls this.setState() which changes the this.state.message value. And when we click the button, here’s how that will play out:

Congrats! You now have a very basic understanding of the most important concepts in React.

If you want to learn more, be sure to check out our free React course on Scrimba.

reactjs javascript

Bootstrap 5 Complete Course with Examples

Bootstrap 5 Tutorial - Bootstrap 5 Crash Course for Beginners

Nest.JS Tutorial for Beginners

Hello Vue 3: A First Look at Vue 3 and the Composition API

Building a simple Applications with Vue 3

Deno Crash Course: Explore Deno and Create a full REST API with Deno

How to Build a Real-time Chat App with Deno and WebSockets

Convert HTML to Markdown Online

HTML entity encoder decoder Online

The essential JavaScript concepts that you should understand

The essential JavaScript concepts that you should understand - For successful developing and to pass a work interview

JavaScript Memory Management System

The main goal of this article is help to readers to understand that how memory management system performs in JavaScript. I will use a shorthand such as GC which means Garbage Collection. When the browsers use Javascript, they need any memory location to store objects, functions, and all other things. Let’s deep in dive that how things going to work in GC.

Mapbox GL Javascript wrapper for ReactJS

react-mapbox-wrapper Mapbox GL Javascript wrapper for ReactJS

JavaScript Expressions in JSX in ReactJs

Welcome, what is JSX Expressions in React Js in Hindi? JSX is an Expression Too After compilation, JSX expressions become regular JavaScript function calls a...

Grokking Call(), Apply() and Bind() Methods in JavaScript

In this article, we will have a look at the call(), apply() and bind() methods of JavaScript. Basically these 3 methods are used to control the invocation of the function.