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:
Describe | Structure |
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
- Passing data from child to parent component in reactjs
- Conditionally add attributes to React components
- useLocation() may be used only in the context of a Router component
- a component is changing an uncontrolled input to be controlled
- useNavigate() may be used only in the context of a Router component
- useRoutes() may be used only in the context of Router component
- Import Aliases When Importing Components
- Component definition is missing display name in React
- Render an Animated GIF in a React component
- Pass an Array as prop to a component in React.js
- Extend an HTML Element in a Component’s props in React
- Import Components from another file in React
- Run a React hook when a component Unmounts
- Call child’s function from a Parent component in React
- Pass Object as props to a component in React TypeScript
React Events
- Call multiple functions onClick in React
- Set the default checked value of a Checkbox in React
- Adding Types to Events in React using TypeScript
- Handle the onKeyPress event in React
- Toggle a class on click in React
- Show an Element on Hover in React
- Handle the Browser Tab close event in React
- Change button text on click in React
- Get data attribute from Event object in React
- Type the onSubmit event in React and TypeScript
- Get the value of an Input on Button click in React
- Set the value of an Input on Button click in React
- Add a Class on hover in React
- Get the key index of an Element on click in React
- Fetch data on Button click in React
- Capture only parent’s onClick event in React
- Check if the Browser tab has Focus using React
- Handle the onPaste event in React (with examples)
- Update a component’s state on Click in React
- Conditionally add an onClick event handler in React
- Scroll to an element on click in React
React Form
- Setting a background image with inline styles in react
- Conditionally setting Styles in React
- Create a Numbers only Input field in React.js
- Draw a horizontal line in React
- Get the Height of an Element using a Ref in React
- Get window width and height in react
- Remove the underline of a Link in React
- Programmatically update query params in React router
- Clear an Input field’s value in React.js
- Submit a form using the Enter key in React.js
- Combine multiple inline Style objects in React
- Display an image from a URL / local path in React
- Get Input value when Enter key is pressed in React
- Get the Width of an Element in React
- How to Prevent form submission in React
- Open page in new tab on button click in React
- Set and Access state using a Dynamic key in React
- How To Handle The OnKeyPress Event In React
- How To Clear An Input Field’s Value In React.js
- How to submit a form using the Enter key in React.js?
- How To Get An Element By ID In React
- Detect When The Esc Key Is Pressed In React.js
- How to check if an Element is focused in React
- How To Center a component horizontally and vertically in React
- Solutions For Setting Data Attributes In React
- How To Create a Back button with React Router
- Argument type ‘HTMLElement or null’ not assignable to parameter type ‘Element or DocumentFragment’ – How to fix it?
- Modify the value of a Textarea using onChange in React
- Find all elements by className in React
- Get the Class name of an element in React
- Set background color with inline Styles in React
- Get the value of an Input field using a Ref in React
- Set CSS display: none conditionally in React
- Prevent multiple Button clicks in React
- How to set the z-index attribute in React
- Add a class to the Body element in React
- How to add a key prop to a React Fragment
- Redirect to another page on button click in React
- Style the border CSS property in React
- Prevent form submission on Enter press in React
- Using !important with inline styles in React
- Avoid unnecessary DIVs when wrapping elements in React
- Using a Ref to change an Element’s style in React
- Reset input field values tracked by useRef in React
- Check if an Input’s value is a valid Number in React
- How to handle visibility: hidden in React
- Setting style for the border radius property in React
- Create numeric input with Min and Max validation in React
- Change the color of a Link in React
- Get the Width of an Element using a Ref in React
- Set a Div’s height to cover the full screen in React
- Using the calc() function in inline styles in React
React Hooks
- Clear a timeout or an interval in React with hooks
- Reset to the initial State using React hooks
- react hook useeffect has a missing dependency error
React useState
- Type useState as Array of Strings in React TypeScript
- Using the useState hook to update boolean state in React
- Type the useState hook with NULL initial value in React
- Set a conditional initial value for useState in React
Other
- How to downgrade React version 16 to 15
- How to downgrade React version 17 to 16
- Adding Types to Refs in React using TypeScript
- Set a Default route with redirect using React Router
- Create a React app in the current directory
- Updating state when props change in React
- Concatenate strings and variables in react
- Get the current URL and Pathname in React
- How to toggle a Boolean state in React
- Update nested properties in a State object in React
- Use a condition inside map() in React
- How to Map through an Object in React
- Sort an Array of Objects in React
- Check if Variable is Undefined in React
- How to Listen for State changes in React
- how to only call a function once in react
- Understanding the exhaustive-deps Eslint rule in React
- Using the map() method with index in React
- Export multiple components from a file in React.js
- How to create a Delay function in React
- How to set Text color in React
- You provided ‘value’ prop to a form field without onChange handler
- React.Children.only expected to receive single React element child
- Pass event and parameter onClick in React
- Pass a Component as props in React
- Import and use an Image in a React component
- Go back to the previous page with React Router
- How To Set Optional Props With Default Values In React
- How To Check If An Array Is Empty In React
- How to generate Option tags for Select from an Array in React
- Check if an Element exists in an Array in React
- Update an Object in an Array in React State
- Use map() on an Array in Reverse Order in React
- Capitalize the first letter of a String in React
- Reset a File input in React
- Generate a random number in React
- Get the Parent height and width in React
- Get the Mouse position (coordinates) in React
- Using the substring() method in React
- Get the First element of an Array in React.js
- Push an element into a state Array in React
- Import Functions from another file in React
- How to merge two Arrays in React.js
- Update an array of objects state in React
- How to pass Functions as Props in React TypeScript
- How to set target=_blank in React
- How to map() only a portion of an Array in React
- Use a map() inside a map() function in React
- How to get the current Year in React
- How to render a boolean value in JSX in React
- Using the find() method in React
- Add an event listener to a Ref in React
- Setting a global font family in React
- Concatenate JSX elements into an Array in React
- Change the default Port for a create-react-app project
- Check if a String is Empty in React
- How to break a map() loop in React
- Where to store images in a React application
- Replace an Object in Array in React state
- How to downgrade React version 18 to 17
- Change the color of an SVG in React
- Find and render Object in Array using React.js
- Using the forEach() method in React
- How to Reverse an Array in React
- Open a link in a new tab in React
- Render nested array using map() in React
- Get the current route using React Router
- Create React App with TypeScript – Complete Guide

Hi guys, wellcome to LearnShareIt. I’m Tiffany and I’m also who responsible for the quality of this website’s content. I previously worked on software development projects for ten years as a developer. Hopefully, our project will bring a lot of value to the community.
Job: Programmer/Project management
Major: IT
Programming Languages: Python, C, HTML, MySQL, SQL Server, C#, C++, Javascript, CSS, Java, VB