Warning: session_start(): open(/tmp/sess_bce6469b90c7c819211a44e77e539c5b, O_RDWR) failed: Disk quota exceeded (122) in /home/wvyrfnwn/learnshareit.com/wp-content/plugins/learnpress/inc/class-lp-page-controller.php on line 1007

Warning: session_start(): Failed to read session data: files (path: /tmp) in /home/wvyrfnwn/learnshareit.com/wp-content/plugins/learnpress/inc/class-lp-page-controller.php on line 1007

Warning: ftp_nlist() expects parameter 1 to be resource, null given in /home/wvyrfnwn/learnshareit.com/wp-admin/includes/class-wp-filesystem-ftpext.php on line 420

Warning: ftp_pwd() expects parameter 1 to be resource, null given in /home/wvyrfnwn/learnshareit.com/wp-admin/includes/class-wp-filesystem-ftpext.php on line 230

Warning: ftp_pwd() expects parameter 1 to be resource, null given in /home/wvyrfnwn/learnshareit.com/wp-admin/includes/class-wp-filesystem-ftpext.php on line 230

Warning: ftp_pwd() expects parameter 1 to be resource, null given in /home/wvyrfnwn/learnshareit.com/wp-admin/includes/class-wp-filesystem-ftpext.php on line 230

Warning: ftp_nlist() expects parameter 1 to be resource, null given in /home/wvyrfnwn/learnshareit.com/wp-admin/includes/class-wp-filesystem-ftpext.php on line 420

Warning: ftp_pwd() expects parameter 1 to be resource, null given in /home/wvyrfnwn/learnshareit.com/wp-admin/includes/class-wp-filesystem-ftpext.php on line 230

Warning: ftp_pwd() expects parameter 1 to be resource, null given in /home/wvyrfnwn/learnshareit.com/wp-admin/includes/class-wp-filesystem-ftpext.php on line 230

Warning: ftp_pwd() expects parameter 1 to be resource, null given in /home/wvyrfnwn/learnshareit.com/wp-admin/includes/class-wp-filesystem-ftpext.php on line 719

Warning: ftp_nlist() expects parameter 1 to be resource, null given in /home/wvyrfnwn/learnshareit.com/wp-admin/includes/class-wp-filesystem-ftpext.php on line 420

Warning: ftp_pwd() expects parameter 1 to be resource, null given in /home/wvyrfnwn/learnshareit.com/wp-admin/includes/class-wp-filesystem-ftpext.php on line 230

Warning: ftp_pwd() expects parameter 1 to be resource, null given in /home/wvyrfnwn/learnshareit.com/wp-admin/includes/class-wp-filesystem-ftpext.php on line 230

Warning: ftp_pwd() expects parameter 1 to be resource, null given in /home/wvyrfnwn/learnshareit.com/wp-admin/includes/class-wp-filesystem-ftpext.php on line 230

Warning: ftp_nlist() expects parameter 1 to be resource, null given in /home/wvyrfnwn/learnshareit.com/wp-admin/includes/class-wp-filesystem-ftpext.php on line 420

Warning: ftp_pwd() expects parameter 1 to be resource, null given in /home/wvyrfnwn/learnshareit.com/wp-admin/includes/class-wp-filesystem-ftpext.php on line 230

Warning: ftp_pwd() expects parameter 1 to be resource, null given in /home/wvyrfnwn/learnshareit.com/wp-admin/includes/class-wp-filesystem-ftpext.php on line 230

Warning: ftp_pwd() expects parameter 1 to be resource, null given in /home/wvyrfnwn/learnshareit.com/wp-admin/includes/class-wp-filesystem-ftpext.php on line 719

Warning: ftp_mkdir() expects parameter 1 to be resource, null given in /home/wvyrfnwn/learnshareit.com/wp-admin/includes/class-wp-filesystem-ftpext.php on line 562

Warning: ftp_nlist() expects parameter 1 to be resource, null given in /home/wvyrfnwn/learnshareit.com/wp-admin/includes/class-wp-filesystem-ftpext.php on line 420

Warning: ftp_pwd() expects parameter 1 to be resource, null given in /home/wvyrfnwn/learnshareit.com/wp-admin/includes/class-wp-filesystem-ftpext.php on line 230

Warning: ftp_pwd() expects parameter 1 to be resource, null given in /home/wvyrfnwn/learnshareit.com/wp-admin/includes/class-wp-filesystem-ftpext.php on line 230
React Tutorial - LearnShareIT

React Tutorial

React Tutorial

In this tutorial, we will focus on sharing the most essential knowledge about React. We will learn React tutorial, what React is, how it works, and commonly used React components.

What is React?

React is a UI library developed by Facebook to support building highly interactive, stateful, and reusable UI components. Note that React is not a js framework at all. 

With the principle of focusing on individual parts, React allows programmers to ‘break’, breaking complex UI interfaces into many simple small parts. This maximizes the development and extension of the web. 

One of the appeals of React is that a library can work and interact right on both sides: the server and the client. The two parties can interact or connect with each other. React makes the programmer aware of changes in the process and it will perform updates on the DOM.

How Does React Work?

In React, the Virtual DOM acts as an intermediary between what the programmer builds and how it is displayed to the user. In order for the user interface to be rendered in the browser, the developer must modify the browser’s DOM (Document Object Model).

However, rewriting the DOM many times will greatly affect the performance. So to not have to change directly on the page interface, React will calculate and change only the important changes through the DOM version installed in memory or in other words a copy of the DOM. At this point, only the important changes will be returned as a result.

As such, how React works can be summed up in two steps:

  • React will proceed to create a virtual DOM. Once the changes are set, React will run the built-in algorithm and determine the changes, which will proceed on the virtual DOM.
  • The second step React will make adjustments and update on the DOM the necessary changes.

React ES6 Classes

ES6 (ECMAScript 6) is considered a collection of advanced JavaScript techniques and is the sixth new version of the ECMAScript standard. The first name when the developer introduced it to the user was ECMAScript 6 (ES6) and then changed to ECMAScript 2015 (ES2015).

This version added new syntax and also important classes and modules for writing complex applications, yet the developer kept the same terminology requirements as ECMAScript 5 (the version known for its rigor).

In addition,  you can use ES6 with other new features including loops, for / of loops, Python-style initializer and initializer expressions, arrow functions, binary data, array inputs, promises , numerical and mathematical enhancements, reflection, and meta-programming for virtual objects.

React Render HTML

Rendering is the rendering of content to the browser. Content can be written from HTML, Javascript or PHP,… The end result is displaying that content on the browser for the user to use. That’s called render.

With React.js, the layout content you write is not located in the HTML page, but is written inside the Javascript file, the HTML file is just a bridge to help the Javascript content “link” with the browser.

In React, we have the ReactDOM.render() function to do the rendering. The return result is the HTML code that will be displayed in the HTML element (these two arguments are specified).

The two parameters used are the HTML code (or the content to display) and the HTML test (or can be considered a container for rendering).

We have a code example like this:

<script type="text/babel">
  ReactDOM.render(<p>LearnShareIT</p>, document.getElementById("root"))
</script>

React reads code like this:

Render p in the <div> with id=”root”.

React JSX

JSX (Javascript XML), is an XML structure written inside a Javascript structure (HTML is also written in an XML structure), so it can be understood more simply than JXS is like writing HTML inside a Javascript structure. Example for a code written in JSX:

const element = (
  <h1 className="StudyIT">LearnShareIT!</h1>
);

Using JSX makes it possible to build React applications that can be built faster, easier to optimize in compiling code to Javascript. 

Some constructs to keep in mind when using JSX:

DescribeStructure
Classname<tag className=””>
<input /> value attribute<input defaultValue=”” />
The for attribute of <label><label htmlFor=””>
Value of <select><option><option value={}>
Style directly inside the tag<tag style={{ width: ‘12%’ }}>
Event<tag onClick={functionName}>
When writing about the value called<img src={path}>LearnIT {name}!

React Components

React Components is one of the most important components in React, it helps to divide the interface (UI) components into smaller components. A page consists of many different components. A React Component is a component that takes props and returns the JSX used to render the user interface.

Each React App can contain many components, each of which usually receives props and returns React elements from which to display to the UI.

In React, there are two types of components: functional components and class components, each of which is used depending on its purpose. Below is a functional component:

const App = () =>  <h1>LearnShareIT.com</h1>;

Before writing components, we should initialize a folder named components in the src folder to contain all the components in the project.

React Class

Class components are ES6 classes. They are more complex than functional components in that they also have: constructor, life-cycle, render() function, and state (data) management. The example below is the class component:

import React, { Component } from 'react';
import { Text } from 'react-native';
export default class WebIT extends Component {
  render() {
    return (
<Text>LearnShareIT</Text>
    );
  }
}

Before declaring a component we need to import React:

import React from 'react';

When you want to write a class component, you must inherit React.Component instead of a function:

class Name extends React.Component {}

A class component must have a render() function. Whatever is returned inside it is rendered as JSX.

class Name extends Component {
  render() {
    return <Text>LearnShareIT</Text>;
  }
}

and finally we need to export components.

export default Name;

React Props

Props is an object passed into a component, each component takes props and returns a react element. Props allow us to communicate between components by passing parameters back and forth between components. Passing a props is the same way you add an attribute to an HTML element.

Here we have an example, passing in each <WebIT> a different name using props.

import React from 'react';
import { Text, View } from 'react-native';
 
function WebIT(props) {
  return (
    <View>
      <Text>Hi, We are {props.name}!</Text>
    </View>
  );
}
 
export default function WebIT() {
  return (
    <View>
      <WebIT name="LearnShareIT" />
    </View>
  );
}

Output:

Hi, We are LearnShareIT!

Most of React Native’s Core Components (React Native pre-built components) can also customize props.

React Events

React events are application reactions, triggered by specific actions from the user such as clicking on a button, moving the mouse over an object.

React events are named with camelCase, instead of lowercase. Example: onclick -> onClick, onchange -> onChange

With JSX, you pass a function to catch the event, instead of a string like regular HTML.

For example:

<button onClick={shoot}>Take the Shot!</button>

You can use an arrow function to pass an argument to an event handler, for example:

function Football() {
  const shoot = (a) => {
    alert(a);
  }

  return (
    <button onClick={() => shoot("Goal!")}>Take the shot!</button>
  );
}

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Football />);

React Conditionals

In React, we can create separate components, and specify which components should be rendered using conditional expressions.

Conditional rendering in React, works similar to regular Javascript, you just need to use the if conditional expression, or conditional operator in Javascript, then React will perform the task of checking the condition and rendering according to the case. request. Here I have an example of checking the user’s login:

import React, { Component } from 'react';
 
export default class App extends Component { 
   render() {
     var isLogin = true
     if(isLogin) {
       return (
         <div>
           <h3>learnshareit.com</h3>
         </div>
       );
     }else{
       return(
         <div>
            <h3>Please login</h3>
         </div>
       )
     }
   }
}

You can use the “if”, “&&” or Ternary operators when you want to render conditional elements.

React Lists

Initializing lists in React is similar to initializing lists in Javascript. Here we will proceed to initialize a list of items:

function Fruits(props) {
  return <li>This is { props.brand }</li>;
}

function Basket() {
  const Fruits = ['Banana', 'Cherry', 'Mango'];
  return (
    <>
      <h1>What is in my basket?</h1>
      <ul>
        {Fruits.map((fruit) => <Fruit brand={fruit} />)}
      </ul>
    </>
  );
}

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Basket />);

Output:

This is Banana
This is Cherry
This is Mango

In the process of working with React, we have to manipulate lists a lot like a list of images, a list of items in the shopping cart, etc. When these lists have dozens of items, React is very difficult to control items. So we need to assign it a key to identify.

For instance:

function Fruit(props) {
  return <li>This is { props.brand }</li>;
}

function Basket() {
  const fruits = [
    {id: 1, brand: 'Banana'},
    {id: 2, brand: 'Cherry'},
    {id: 3, brand: 'Mango'}
  ];

  return (
    <>
      <h1>What is in my basket?</h1>
      <ul>
        {fruits.map((fruit) => <Fruit key={fruit.id} brand={fruit.brand} />)}
      </ul>
    </>
  );
}

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Basket />);

React Forms

We can use form elements in HTML pages, but to take advantage of React, as well as being able to handle data easily, React chooses to write form components inside a Javascript file. This technique is called a “controlled component”.

Values changed in the form will be kept in the state of the component, and updated via setState.

Form operations in ReactJS are usually: Get the value of input, Submit Form and Validation Form.

For example:

import { useState } from "react";
import ReactDOM from 'react-dom/client';
 
const Form=()=> {
  const [name, setName] = useState();
  const [fullName,setfullName]= useState();
const handleBtnSubmit = (e)=>{
  e.preventDefault();
 setfullName(name)
}
 
const handleChangeText = (e)=>{
  e.preventDefault();
  setName(e.target.value)
}
 
  return (<>
    <form onSubmit={handleBtnSubmit}>
   
      <label><h1>Hello From Learn Share IT</h1>
        What is your name:
        <input
          type="text"
          value={name}
          onChange={handleChangeText}
        />
      </label>
      <button type={'submit'}>Submit</button>
    </form>
    <h1>Your name is:<span>{fullName}</span></h1>
    </>)
}
 
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Form />); 

Output:

Explain:

We can get the input’s value by catching the input’s onChange event. When the onChange event is triggered, we will have a variable called event, which will contain input information such as name, value,… Here I pass the event variable into the changeInputValue() function.

Then, we will build the changeInputValue() function to change the state (which will store the value of the input) that we initialized earlier.

After getting the input value, the form needs to be submitted, you can submit the form by catching the onSubmit event in the form.

When the onSubmit event is executed, the event variable containing the form’s information will exist, we will pass it into the submitForm() function for processing.

React Router

React Router is a library for standard URL navigation in React, It allows us to synchronize the UI with the URL. Designed with a simple API in mind, allowing quick URL issues to be resolved.

To use React Router we need to install this library into our React project using NPM:

npm install react-router-dom

After successful installation, in case you need to use React Router you just need to import that component.

import { BrowserRouter, Route, Switch } from 'react-router-dom';

React Memo

To improve the performance of a website using React, we can improve it by limiting unnecessary re-renders. To do that, React introduces a feature called React.memo().

React.memo() will help us to limit re-renders by checking if the component’s props have changed.

When a component is wrapped by React.memo(), React will remember (memoize) the result of this render, and before the next render, if the new props are unchanged from the last memory, React will reuse the result. As a result, it remembered and skipped this render.

React CSS Styling

In React, applications or components can be individually styled through CSS. By using the Style property, the programmer can completely add styles to the elements. Some commonly used ways when styling in React with CSS like:

  • Inline styling
  • CSS Stylesheet
  • CSS Modules
  • Styled Components

For example:

const Header = () => {
  return (
    <>
      <h1 style={{color: "red"}}>Hello LearnShareIT</h1>
      <p>We learn to code!</p>
    </>
  );
}

React Sass Styling

SASS is a CSS Processor that supports CSS code management, this is a pretty good library that you should use to manage your source code. The code of SASS is very similar to a programming language so it is concise and clean, so it is very beneficial for large projects to use it. When using SASS, the browser will not understand it, so we have to go through the stage of compiling the SASS file into a CSS file and this job requires us to install a third software. Third-party software uses Ruby to compile, so it requires you to install Ruby to use it.

To install SASS, run the command: 

>npm i sass

Here is a code used to color text using SASS:

import React from 'react';
import ReactDOM from 'react-dom/client';
import './my-sass.scss';

const Header = () => {
  return (
    <>
      <h1>Hello LearnShareIT!</h1>
      <p>We learn to code!.</p>
    </>
  );
}

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Header />);

my-sass.scss:

$myColor: red;
h1 {
  color: $myColor;
}

Thus, we have introduced you to the necessary knowledge when getting started with React. With certain basic knowledge you will handle situations easily.

React Tutorial

Below we have compiled a list of tutorials related to React that may be of interest to you:

React Component

React Events

React Form

React Hooks

React useState

Other

Leave a Reply

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