MOST In-DEMAND React JS Tutorial [ STEP-IN ] | Learn Now
REACT JS Tutorial

MOST In-DEMAND React JS Tutorial [ STEP-IN ] | Learn Now

Last updated on 11th Jun 2020, Blog, Tutorials

About author

Jesica Parveen (Full Stack Developer )

Jesica Parveen has 8+ years of Full Stack Developer expertise in HTML, CSS, JavaScript, jQuery, CSS, SEO, facing UI, and back. She has skills in Servlet and JSP development, CSS, JavaScript, HTML, AJAX, jQuery, EXTJS, OSGi/FELIX, CMS development experience, Java Content Repository (JCR), Eclipse IDE.

(5.0) | 19007 Ratings 1864

ReactJS Tutorial

ReactJS Tutorial-React JS Tutorial
  • ReactJS tutorial provides basic and advanced concepts of ReactJS. Currently, ReactJS is one of the most popular JavaScript front-end libraries which has a strong foundation and a large community.
  • ReactJS is a declarative, efficient, and flexible JavaScript library for building reusable UI components. It is an open-source, component-based front end library which is responsible only for the view layer of the application. It was initially developed and maintained by Facebook and later used in its products like WhatsApp & Instagram.
  • Our ReactJS tutorial includes all the topics which help to learn ReactJS. These are ReactJS Introduction, ReactJS Features, ReactJS Installation, Pros and Cons of ReactJS, ReactJS JSX, ReactJS Components, ReactJS State, ReactJS Props, ReactJS Forms, ReactJS Events, ReactJS Animation and many more.
Subscribe For Free Demo

What Is React?

React is a declarative, efficient, and flexible JavaScript library for building user interfaces. It lets you compose complex UIs from small and isolated pieces of code called “components”.

Evolution Of React

  • React is a JavaScript library used to build the user interface for web applications. React was initially developed and maintained by the folks at Facebook, which was later used in their products (WhatsApp & Instagram). Now it is an open source project with an active developer community. Popular websites like Netflix, Airbnb, Yahoo!Mail, KhanAcademy, Dropbox and many more use React to build their UI. Modern websites are built using MVC (model view controller) architecture. React is the ‘V’ in the MVC which stands for view, whereas the architecture is provided by Redux or Flux. React native is used to develop mobile apps, the Facebook mobile app is built using React native.
  • Facebook’s annual F8 Developer conference 2017, saw two promising announcements: React Fiber and ReactVR. React Fiber is a complete rewrite of the previous release focusing on incremental rendering and quick responsiveness, React Fiber is backward compatible with all previous versions. ReactVR is built on top of React Native frameworks, it enables developing UI with the addition of 3D models to replicate 360-degree environment resulting in fully immersive VR content.

Why Learn React?

React is among the easiest JS libraries you can start with. Conventional Vanilla JavaScript is more time-consuming, why waste time writing lengthy code when u can get things done smoothly with React. React has over 71,200 stars on GitHub, making it the 4th most starred project of all time. After looking at the below example, I am sure you would understand why front-end developers across the world are switching to React. Now let’s try coding a set of nested lists in React and compare it with conventional JavaScript syntax.

React Features Overview

React Features Overview-React JS Tutorial

Figure: ReactJS Tutorial – React Features

Learning Curve

React has a shallow learning curve and it is suitable for beginners. ES6 syntax is easier to manage especially for smaller to-do apps. In React, you code in the ‘JavaScript’ way, giving you the freedom to choose your tool depending upon your need. Angular expects you to learn one additional tool ‘typescript’ which can be viewed as the ‘Angular’ way of doing things. In ‘Angular’ you need to learn the entire framework even if you’re just building a simple UI application.

Concept: The Simplicity Of Virtual DOM

Learning Curve-React JS Tutorial

Figure : ReactJS Tutorial – React Virtual DOM

In contrary to the actual DOM, react makes use of the Virtual DOM. Virtual DOM utilizes a differential algorithm for making calculations. This relieves the real DOM which can then process other tasks. Let me illustrate this with an example.

Now consider there are 10,000 nodes out of which we only need to work on 2 nodes. Now most of the processing is wasted in traversing those 10,000 nodes while we only operate on 2 nodes. The calculations are done by the Virtual DOM to find those 2 nodes and the real DOM quickly retrieves them.

Performance

When it comes to performance, React sits right at the top. React is known for its superior rendering speed. Thus the name “React”, an instant reaction to change with minimum delay. DOM manipulation is the heart of a responsive website, unfortunately it is slow in most JavaScript frameworks. However, Virtual DOM is implemented in React, hence it is the underlying principle behind React’s superior performance.

Size

As we already know, React is not a framework, thus features may be added according to the user’s needs. This is the principle behind the light-weight applications built on React – pick only what is needed. Webpack offers several plugins which further minimize (minify) the size during production, The React + Redux bundle minified constitutes around 200 kb whereas its rival Angular is almost four times bigger (Angular + RxJS bundle).

Debugging

There will be a point when a developer goes through a roadblock. It could be as simple as a ‘missing bracket’ or as tricky as a ‘segmentation fault’. In any case, the earlier the exception is caught the lesser is the cost overhead. React uses compile time debugging and detects errors at an early stage. This ensures that errors don’t silently turn up at run-time. Facebook’s unidirectional data flow allows clean and smooth debugging, fewer stack traces, lesser clutter and an organized Flux architecture for bigger applications.

How Does It Work?

While React is easier to learn for beginners with no prior JavaScript experience, the nitty gritty’s of transpiling JSX code can often be overwhelming. This sets the tone for tools such as Babel and Webpack. Webpack and Babel bundle together all the JavaScript files into a single file. Just like how we use to include a link to the CSS and JS files in our HTML code, Webpack performs a similar function eliminating the need for explicitly linking files.

I’m sure all of you use Facebook. Now, imagine Facebook being split into components, each functionality is assigned to a specific component and each component produces some HTML which is rendered as output by the DOM. 

Facebook Components

  • Search Bar
  • Add Post 
  • Notifications Bar 
  • Feed Updates
  • Profile Info
  • Chat Window

Building Blocks:-

  • Components
  • Props
  • State
  • State Lifecycle
  • Event handling 
  • Keys

Moving on to the core aspect of our ReactJS tutorial, let us discuss the building blocks of React.

Components

The entire application can be modeled as a set of independent components. Different components are used to serve different purposes. This enables us to keep logic and views separate. React renders multiple components simultaneously. Components can be either stateful or stateless.

Before we start creating components, we need to include a few ‘import’ statements.

In the first line, we have to instruct JavaScript to import the ‘react’ library from the installed ‘npm’ module. This takes care of all the dependencies needed by React.

Course Curriculum

Enroll in React JS Certification Course to Build Your Skills & Advance Your Career

Weekday / Weekend BatchesSee Batch Details

State

“And I believe state adds the greatest value to React.”

State allows us to create components that are dynamic and interactive. State is private, it must not be manipulated from the outside. Also, it is important to know when to use ‘state’, it is generally used with data that is bound to change. For example, when we click a toggle button it changes from ‘inactive’ to ‘active’ state. State is used only when needed, make sure it is used in render() otherwise don’t include it in the state. We do not use ‘state’ with static components. The state can only be set inside the constructor. Let’s include some code snippets to explain the same.

  • class Toggle extends React.
  • Component
  • {
  • constructor(value)
  • {super(value);this.state = {isToggleOn: true};
  • this.handleClick = this.handleClick.bind(this);
  • }

Binding is needed explicitly, as by default the event is not bound to the component.

Event Handling And Manipulation Of State 

Whenever an event such as a button click or a mouse hover occurs, we need to handle these events and perform the appropriate actions. This is done using event handlers.

While State is set only once inside the constructor it can however, be manipulated through “setState” command. Whenever we call “handleclick” function based on the previous state, “isToggleOn” function is switched between “active” and “inactive” state.

  • handleClick()
  • {
  • this.setState(prevState =>
  • ({isToggleOn: !prevState.isToggleOn}));
  • }

The OnClick attribute specifies the function to be executed when the target element is clicked. In our example, whenever “onclick” is heard, we are telling React to transfer control to handleClick() which switches between the two states.

  • render()
  • {
  • return(<button onClick={this.handleClick}>{this.state.isToggleOn ?
  • ‘ON’: ‘OFF’} );
  • }}// end class

React has a few different kinds of components, but we’ll start with React.Component subclasses:

  • class ShoppingList extends React.Component {
  •   render() {
  •     return (
  •       <div className=”shopping-list”>
  •         <h1>Shopping List for {this.props.name}</h1>
  •         <ul>
  •           <li>Instagram</li>
  •           <li>WhatsApp</li>
  •           <li>Oculus</li>
  •         </ul>
  •       </div>
  •     );
  •   }
  • }

// Example usage: <ShoppingList name=”Mark” />

  • We’ll get to the funny XML-like tags soon. We use components to tell React what we want to see on the screen. When our data changes, React will efficiently update and re-render our components.
  • Here, ShoppingList is a React component class, or React component type. A component takes in parameters, called props (short for “properties”), and returns a hierarchy of views to display via the render method.
  • The render method returns a description of what you want to see on the screen. React takes the description and displays the result. In particular, render returns a React element, which is a lightweight description of what to render. Most React developers use a special syntax called “JSX” which makes these structures easier to write. The <div /> syntax is transformed at build time to React.createElement(‘div’). The example above is equivalent to:
  • return React.createElement(‘div’, {className: ‘shopping-list’},
  •   React.createElement(‘h1’, /* … h1 children … */),
  •   React.createElement(‘ul’, /* … ul children … */)
  • );

See full expanded version.

  • If you’re curious, createElement() is described in more detail in the API reference, but we won’t be using it in this tutorial. Instead, we will keep using JSX.
  • JSX comes with the full power of JavaScript. You can put any JavaScript expressions within braces inside JSX. Each React element is a JavaScript object that you can store in a variable or pass around in your program.
  • The ShoppingList component above only renders built-in DOM components like <div /> and <li />. But you can compose and render custom React components too. For example, we can now refer to the whole shopping list by writing <ShoppingList />. Each React component is encapsulated and can operate independently; this allows you to build complex UIs from simple components.

Inspecting the Starter Code

  • If you’re going to work on the tutorial in your browser, open this code in a new tab: Starter Code. If you’re going to work on the tutorial locally, instead open src/index.js in your project folder (you have already touched this file during the setup).
  • This Starter Code is the base of what we’re building. We’ve provided the CSS styling so that you only need to focus on learning React and programming the tic-tac-toe game.

By inspecting the code, you’ll notice that we have three React components:

  • Square
  • Board
  • Game

The Square component renders a single <button> and the Board renders 9 squares. The Game component renders a board with placeholder values which we’ll modify later. There are currently no interactive components.

Passing Data Through Props

  • To get our feet wet, let’s try passing some data from our Board component to our Square component.
  • We strongly recommend typing code by hand as you’re working through the tutorial and not using copy/paste. This will help you develop muscle memory and a stronger understanding.

In Board’s renderSquare method, change the code to pass a prop called value to the Square:

  • class Board extends React.Component {
  •   renderSquare(i) {
  •    return <Square value={i} />;
  •  }
  • }

Change Square’s render method to show that value by replacing {/* TODO */} with {this.props.value}:

  • class Square extends React.Component {
  •   render() {
  •     return (
  •       <button className=”square”>
  •        {this.props.value}
  •      </button>
  •     );
  •   }
  • }

Before:

React JS Tutorial

After: You should see a number in each square in the rendered output.

React JS Tutorial
  • Congratulations! You’ve just “passed a prop” from a parent Board component to a child Square component. Passing props is how information flows in React apps, from parents to children.
  • Making an Interactive Component

Let’s fill the Square component with an “X” when we click it. First, change the button tag that is returned from the Square component’s render() function to this:

  • class Square extends React.Component {
  •   render() {
  •     return (
  •      <button className=”square” onClick={function() { alert(‘click’); }}>
  •        {this.props.value}
  •       </button>
  •     );
  •   }
  • }

If you click on a Square now, you should see an alert in your browser.

ReactJS Sample Resumes! Download & Edit, Get Noticed by Top Employers! Download

Note

To save typing and avoid the confusing behavior of this, we will use the arrow function syntax for event handlers here and further below:

  • class Square extends React.Component {
  •  render() {
  •    return (
  •     <button className=”square” onClick={() => alert(‘click’)}>
  •       {this.props.value}
  •      </button>
  •    );
  •  }
  • }
  • Notice how with onClick={() => alert(‘click’)}, we’re passing a function as the onClick prop. React will only call this function after a click. Forgetting () => and writing onClick={alert(‘click’)} is a common mistake, and would fire the alert every time the component re-renders.
  • As a next step, we want the Square component to “remember” that it got clicked, and fill it with an “X” mark. To “remember” things, components use state.
  • React components can have state by setting this.state in their constructors. this.state should be considered as private to a React component that it’s defined in. Let’s store the current value of the Square in this.state, and change it when the Square is clicked.

First, we’ll add a constructor to the class to initialize the state:

  • class Square extends React.Component {
  •  constructor(props) {
  •    super(props);
  •    this.state = {
  •      value: null,
  •    };
  •  }
  •   render() {
  •     return (
  •       <button className=”square” onClick={() => alert(‘click’)}
  •         {this.props.value}
  •       </button>
  •     );
  •   }
  • }

Note

In JavaScript classes, you need to always call super when defining the constructor of a subclass. All React component classes that have a constructor should start with a super(props) call.

Now we’ll change the Square’s render method to display the current state’s value when clicked:

  • Replace this.props.value with this.state.value inside the <button> tag.
  • Replace the onClick={…} event handler with onClick={() => this.setState({value: ‘X’})}.
  • Put the className and onClick props on separate lines for better readability.

After these changes, the <button> tag that is returned by the Square’s render method looks like this:

  • class Square extends React.Component {
  •   constructor(props) {
  •     super(props);
  •     this.state = {
  •       value: null,
  •     };
  •   }
  •   render() {
  •     return (
  •      <button
  •      className=”square”
  •       onClick={() => this.setState({value: ‘X’})}
  •      >
  •        {this.state.value}
  •      </button>
  •     );
  •   }
  • }

By calling this.setState from an onClick handler in the Square’s render method, we tell React to re-render that Square whenever its <button> is clicked. After the update, the Square’s this.state.value will be ‘X’, so we’ll see the X on the game board. If you click on any Square, an X should show up.

Are you looking training with Right Jobs?

Contact Us
Get Training Quote for Free