Introduction
React JS is a conclusive library maintained by Facebook and a vast community of individual developers. It is an open-source JavaScript library mostly used to develop frontends for single-page applications and websites. Well, applications and websites like Facebook, Instagram, Netflix, PayPal, and many more are built using React library. React JavaScript is an indisputably great language for programming sites and applications; hence, it is extremely popular among the developer community.
Features of React JS
The finest JavaScript framework right now among web developers is ReactJS, which is quickly gaining popularity. It’s very popular in front-end ecosystems. The features of React are as follows.
JSX
JSX is also referred to as Javascript XML. It is an extension of the regular Javascript syntax. JSX is analogous to HTML or XML as both have the same syntax. Using JSX isn’t mandatory, but it has proven easy and useful. In React, the syntax of JSX is processed into Javascript calls. JSX is an extension of ES6, which allows HTML-like text and JavaScript react code to exist together.
[Also Read, Memoization Methods in React JS]
Components
Components are the foremost important feature of React JS. A simple React application is broken down into smaller components. Each Component has different controls and logic. We can use those components as classes as well as functions. These components are useful in complex projects as they are reusable.
Class component returns HTML and uses extends React.Component, which allows the current Component to access all its properties.
class Panda extends React.Component {
render() {
return <h2>Hi, I am a Panda!</h2>;
}
}
Function components also return HTML but are more precise and hence easier to write.
function Panda() {
return <h2>Hi, I am a Panda!</h2>;
}
Virtual DOM
DOM is Document Object Model. The original DOM object’s virtual representation is called Virtual DOM. The entire user interface is rerendered in virtual DOM representation every time modifications are made to the web application. Then it compares the dissimilarities between the old and new DOM representations. Once the comparison is done, only the changed elements are updated by the DOM. This results in less memory consumption, and the application runs faster.
Unidirectional data flow
Unidirectional data flow means when data travels in different parts of a program, it can flow in only one direction. In React, we nest the components inside each other forming various child and parent components according to the hierarchy. The data transfer in these components is one way. More precisely, the data is transferred from the parent component to the child component, not vice versa. The child components are not allowed to modify the data coming from the parent components. The one-course binding makes debugging easier as we know where data comes from. The program is less error-prone and hence more efficient.
Constructor and Super with class component
Constructors are the methods that are called automatically during the creation of an object by a class. A constructor initializes the state of an object by assigning it to this.state. It binds event handler methods that occur in your Component. In React, the constructor is called during the creation of the Component and before mounting. While implementing the constructor for a React component, you must call the super(props) method prior to any other statement. Else, this.props will not be defined in the constructor and create bugs. The usage of super(props) is quite simple. You have to call it in the constructor method of your child component for Example:
constructor(props) {
super(props);
console.log(this.props);
}
Example of constructors in react:
import React, { Component } from "react";
class App extends Component {
constructor(props) {
super(props);
this.state = {
todo: "Do your Homework"
};
this.handleEvent = this.handleEvent.bind(this);
}
handleEvent() {
this.setState({ todo: `It's Done` });
}
render() {
return (
<div className="App">
<h2>MY TODOLIST</h2>
<p>{this.state.todo}</p>
<button onClick={this.handleEvent}>Update Todo</button>
</div>
);
}
}
export default App;
Creating React Application
You need npm and Node.js installed to use React production and write the React code directly into the HTML file. The command to create a React application named MyApp is as follows:
npx create-react-app myapp
Once the application is created, move inside the application’s directory and use the following command to run the application:
npm start
Importing and Exporting Components
One of the most prominent features of React is the reusability of components. While nesting, making different files for different components becomes necessary to keep the code clean and understandable. Now to reuse these components, you need to export your Component from the file where it is present and import it into the file where you’ll use it. We use the keyword export to export a particular code module or a parameter in react.
Default export:
We can import the default export with any name. Every module should have only one default export. We need to follow the syntax described below to export the default export from a file.
// file component1.js
const c = 100;
export default c;
// file main.js
import t from './component1';
// as c was a default export we can use t instead of c
console.log(t); // output 100
Named export:
Named exports are useful when you want to export more than one value at once. While importing the named exports they should be referred by the same name. We can have more than one named export. To export one, we should use the syntax as follows :
export const c= 100;// more than one export
export function Myfunction() {
console.log('This is a Named Export');
}
// importing in another file
import { c, Myfunction} from './Myfunction';
Myfunction(); // Output: 'This is a Named Export'
console.log(c); // Output: 100
State in React JS
The state is a predefined React object that holds the information about the Component. A component’s state is not fixed. The state is changed due to users’ actions or system-generated events. Each time the state changes, the component re-renders. For Example, a mammal component can have legs as a state and we can access this state by this.state.clicked
class Mammal extends Component {
constructor(props) {
super(props)
this.state = { legs: 4 }
}
render() {
return (
<div>
<p>legs: {this.state.legs}</p>
</div>
)
}
}
Direct modification of state might cause errors; instead, you should use setState(). Using setState() rerenders the Component, and your code is consistent with the React’s.
this.setState({ legs: 2 })
Props in React JS
The props are a type of object in which the value of attributes of a tag is stored. They are basically like function arguments in JavaScript. Props are used to pass the data from parent to child components as parameters. For the function component, we just have to pass the props as a parameter and they are available by adding props as the function argument:
import Myclass from "./Cmp1";
import MyFunction from "./Cmp2";
export default function App() {
return (
<div className="App">
<Myclass
title="React Tutorial"
description="Lorem ipsum, or lipsum as it is sometimes"
/>
<MyFunction
title="Redux Tutorial"
description="Lorem ipsum, or lipsum as it is sometimes"
/>
</div>
);
}
const MyFunction = props => {
return (
<div>
<h1>{props.title}</h1>
<p>{props.description}</p>
</div>
)
}
export default MyFunction;
In class component, you can access the props using this.props without adding the function argument:
class Myclass extends Component {
render() {
return (
<div>
<h1>{this.props.title}</h1>
<p>{this.props.description}</p>
</div>
)
}
}
export default Myclass;
Lifecycle of a Component
The lifecycle of react components includes four stages. Every Component goes through Initialization, Mounting, Update, and UnMounting stages.
- Initialization is the first stage, with initial state levels and default props.
- The mounting phase is the component formation phase, where components are created and mounted together for running the application. Components are rendered in DOM during this phase.
- Updating phase represents times when a component needs to update due to a change in its props or state. The changes can occur within the component or through the backend. Once the changes are done the components rerender.
- Unmounting is the last phase of the lifecycle in which it is removed from the DOM when it is no longer needed.
Advantages of React JS
- One major advantage of React is it is relatively simple to learn and deploy.
- The reusable components used in react accelerate the entire development process. They can be nested within each other and used as simple building blocks to complex applications.
- React developer tools include Firefox developer extension that allows for analyzing component hierarchies of the react in virtual DOM which makes the process more understandable.
- You don’t have to worry about the complex internal working of the internal functions. The abstraction is very well maintained.
- As the data flow is in a downward direction, any changes in the parent component has no effect on the child components. This facilitates debugging for developers.
- The scope of code testing is more with various platforms like Jest and Enzyme.
Disadvantages of React JS
- React is one the continuously changing technologies which makes it complicated to catch up with the documentation.
- The intricacies of the learning curve of JSX are cumbersome for the beginner developers.
- You’ll need to use extra tools to handle other crucial components like the data storage and backend in order to build a successful app.
- The file size of ReactJS is large.
Summary
- React.js is a frontend JavaScript framework developed by Meta. It is used in building interactive User Interfaces in a component-based manner.
- JSX, which is Javascript XML, is used to write Javascript and HTML together.
- React is based on the concept of components. They are independent bits of code that can be reused.
- Virtual DOM is basically a virtual representation of the original DOM object. It is used for minimum memory consumption.
- Between the components nested inside each other, the data can flow only from parent to the child components. Child components cannot modify the incoming data.
- Constructors are user defined objects.
- State is a predefined object that contains the information about a component.
- Props are the type of objects that are used to pass data from parent to child.
- Initialization, Mounting, Update, and UnMounting are the four stages of a components lifecycle.
Thanks for reading React JS Tutorial for Beginners. Hope you found this article helpful.
2 comments
Comments are closed.