React Crash Course: Learn Basic React Concepts In 30 Minutes [Practical]

A small and simple application is the better way to learn React’s basic concepts. In this React Crash Course, you will get a fair idea about how React works and some of its basic concept that makes up React.

React Crash Course for Beginner



After reading this article you will become Beginner React Developer.

First, Let’s go through what we are going to build and what React concepts you are going to learn.

What You are Going to Learn?

  • What is React?
  • How to Use React?
  • How to Create a Component?
  • How to Use JSX?
  • How to Use Local State in React?
  • How to Use and Bind Events in React?
  • How to Render Component?



What We are Going to Build?

We are going to build a simple Score Board Application in which you can increase and decrease score.

Requirements

  • Basic Knowledge of HTML and JavaScript ES5 Features
  • Visual Studio Code Editor



What is React?

As per react.org, “React is a javascript library for building user interfaces“. We have written an article on React. Go through it to get deep knowledge about React.

How to Use React?

There are many ways to setup React. But the most common way is to use create-react-app with Visual Studio Code Editor.

1] Install Node.js on your computer. Follow only Step 1 and Step 2 from this article.

2] Download and install the Visual Studio Code (VS Code).

3] Open VS Code. Click on the Terminal menu. Select New Terminal.

Note: Don’t use command prompt from windows as shown in the below steps. Use opened terminal from VS code only.

4] In this article, there are steps given to setup create-react-app. Follow only Step 2 (start with 2nd point) from the article. While using create-react-app command give ‘scoreboard’ name to the application instead of myreactapp.

How to Create a Component?

We hope that you have setup create-react-app and ran it successfully. Now follow the below steps to create a component.

1] Come to app.js file. You would see the below code. Remove the highlighted part from code.

React Crash Course - Remove Code



2] Add below code in the app.js.

 
  class Scoreboard extends React.Component
  {
    render() {
       return (
         
) } }

This is Scoreboard component. A component is the most important feature in React. Whole react application made up of small components working together to build a large application. Components are of two types class and function components. We are using a class component in this React course.

If you look at the above code you can see that class Scoreboard extends from React.component. Any class that needs to be work as a component has to extend React.component class.

Every component class has a render() function inside it. Which renders component first time and when its state gets changed. Render method returns JSX code. JSX has to have at least one parent element.

Here is the full Component code for the scoreboard application. Just go through it once and then read explanation. Put this code into app.js.

 
  import React from 'react';

  class Scoreboard extends React.Component
  {
    constructor(props){
     super(props);
     this.state={score:0};
     this.incrementScore=this.incrementScore.bind(this);
     this.decrementScore=this.decrementScore.bind(this);
    }
  
    incrementScore() {
       this.setState({
       score:this.state.score + 1
      })  
    }

    decrementScore() {
      this.setState({
      score:this.state.score - 1
      })
    }
     render() {
       return (
         

Scoreboard of {this.props.team}

Score: {this.state.score}

) } } export default Scoreboard;

Let’s start with the render() function.

render function returning <h1> tag which displays name of the team which comes from the props while rendering component. (Note: We will see how to render the component in next section).

props are basically parameter accept by the component. props pass JSX attributes to the component as a single object.

How to Use JSX?

JSX code is the extension of javascript. Whatever you can see in the render() function is JSX. It looks like HTML but it’s NOT. In React, JSX automatically compiles down to the React.createElement() calls by Babel and further down to react elements which then use by React virtual DOM to construct and compare Real DOM.

Here is an example.

JSX:

 
   const element = (
      

Hello, world!

);

Babel converts JSX to React.createElement() Calls

 
   const element = React.createElement(
     'h1',
     {className: 'greeting'},
     'Hello, world!'
   );

Finally, Create elements call creates an object called React Element.

 
   const element = {
     type: 'h1',
     props: {
     className: 'greeting',
     children: 'Hello, world!'
     }
   };

You don’t need to worry about Babel if you have setup create-react-app. It comes up with Babel integration. Still, in our future articles, we will cover how to setup Babel in your application manually to work with JSX.

How to Use Local State in React?

In the child <div> of the render() method, we are displaying score from the local state of a scoreboard component.

Each and every component has its own local state. We store state value/object into the special object called state. In the class constructor, we have set an initial state of scoreboard component to 0 ( this.state={score:0}; ). As constructor executes only one time, (at the time of object initialization) the initial score will set to 0.

In the render method, we are displaying the value of score from the state object.

We also have two buttons. One for increment and another for decrement. We need event handler to handle this increment and decrement of the score. So on the onClick event on both buttons, we are calling incrementScore and decrementScore methods/events/functions.

In the incrementScore function, we are setting up the state again to increment the original state value by 1 and in decrementScore we are decrementing value by 1. We are using setState() function to set state.

ALWAYS REMEMBER!!! DO NOT modify state directly. The state has already been set in the constructor. DO NOT modify state again like that (as we did in the constructor). If you try to modify state as we did in the constructor then you will not get updated value on UI as render method of a component didn’t call.

That is why use setState() function to modify state so the render function will load again and you can see the latest value.

How to Use and Bind Events in React?

In the constructor, you must have seen that we have binding ‘this‘ to both event handlers. Reason being, as you know ‘this‘ refers to the current object in javascript. You can see both events are in the component class Scoreboard but they are not attached to the object in any way.

For example, we are NOT calling any of the events like the below code.

 
  Scoreboard objScore = new Scoreboard();
  objScore.incrementScore();
  objScore.decrementScore();  

If we would have done this than events must have access to ‘this‘. Read this article to know more about it.

How to Render Component?

Rendering component is very easy. We use ReactDOM.render() method to render component. It takes two parameters, first component name and second HTML element where components need to be rendered.

Before accessing any component to another .js file you need to export component. You can see in the app.js file outside the Scoreboard component class we call written below code.

 
 export default Scoreboard;

and to access this component you need to import this to .js file you are using. In the index.js file put this import line.

 
 import Scoreboard from './App';

Note: If this line is already there then you just need to replace the old component name which you have removed with Scoreboard.

Now put below code in index.js file. This code will render the Scoreboard component in the root div element of index.html file. You would find this .html file in /public folder.

 
 ReactDOM.render(, 
 document.getElementById('root'));

Additional knowledge: Props

In the above code, We have passed parameter to the Scoreboard component (team=”Barcelona fc” ). This is called props and this can be accessed in the component using special object ‘props‘ (this.props.team). You can see we are displaying team name in the render method of the component.

Note: Before using props you must pass it to super() and constructor of component. See the constructor of Scoreboard component.

So that’s it. We have successfully created a Scoreboard application by using all basic concepts of React. Here is the full working code.

App.js

 
  import React from 'react';

  class Scoreboard extends React.Component
  {
      constructor(props) {
        super(props);
        this.state={score:0};
        this.incrementScore=this.incrementScore.bind(this);
        this.decrementScore=this.decrementScore.bind(this);
      }
  
      incrementScore() {
        this.setState({
         score:this.state.score + 1
        })  
      }

      decrementScore() {
        this.setState({
         score:this.state.score - 1
        })
      }
     
      render() {
        return  (
          

Scoreboard of {this.props.team}

Score: {this.state.score}

) } } export default Scoreboard;

index.js

 
  import React from 'react';
  import ReactDOM from 'react-dom';
  import Scoreboard from './App';
  import * as serviceWorker from './serviceWorker';

  ReactDOM.render(, 
  document.getElementById('root'));

  // If you want your app to work offline and load faster, you can change
  // unregister() to register() below. Note this comes with some pitfalls.
  // Learn more about service workers: https://bit.ly/CRA-PWA
  serviceWorker.unregister();

index.html

 
  
  
    
      
      
      
      
      
   
      
     
      React App
    
    
      
      

If you have any kind of doubt please mention that below in comments.

Admin

Tutorial Funda will keep you updated with the latest Programming Languages, Software Tools and related technologies used in Software Development.

Leave a Reply

Your email address will not be published. Required fields are marked *