cover-img

React Basic Concepts

18 May, 2023

0

0

0

React Basic Concepts

Untitled

React is a declarative, efficient, and flexible Javascript library for building user interfaces. But instead of using regular JavaScript, React code is written in JSX.

JSX(JavaScript XML) is a syntax extension of regular JavaScript and is used to create React elements. These elements are then rendered to the React DOM

Why JSX?

  • It’s faster than normal Javascript as it performs optimizations while translating regular JavaScript.
  • It makes it easier for us to create templates.
  • Instead of separating the markup and logic in separate files, React uses components for this purpose.
  • As JSX is an expression we can use it inside of if statements and for loops, assign it to variables, accept it as arguments or return it from functions.

In React we are allowed to use normal Javascript expressions with JSX. To embed any JavaScript expression in a piece of code written in JSX we wrap that expression in curly braces {}.

JSX allows us to use attributes with the HTML elements just like we do with normal HTML. But instead of the normal naming convention of HTML, JSX uses the camelcase convention for attributes. For example, a class in HTML becomes a className in JSX. The main reason behind this is that some attribute names in HTML like ‘class’ are reserved keywords in JavaScript. So, to avoid this problem, JSX uses the camel case naming convention for attributes.

JSX allows us to specify attribute values in two ways:

  1. As for string literals: We can specify the values of attributes as hard-coded strings using quotes:
const ele = <h1 className ="firstAttribute">Hello</h1>
  1. As expressions: We can specify the values of attributes as expressions using curly braces{}:
const ele = <h1 className={vaName}>Hello!</h1>

When you want to render multiple tags at the same time you need to wrap all of these tags under a parent tag and then render this parent element to the HTML. All the subtags are called child tags or children of this parent element.

JSX allows us to use comments as it allows us to use JavsScript expressions, comments in JSX begin with /* and end with */. We can add comments in JSX by wrapping them in curly braces {} just like we did in the case of expressions.

React element is the smallest renderable unit available in React, we can render such elements using ReactDOM. React elements are different from DOM elements as React elements are simple Javascript objects and are efficient to create. React elements are the building blocks of any React app and should not be confused with React components.

To render an element into the Browser DOM, we need to have a container or root DOM element. It is almost a convention to have a div element with id=” root” or id=” app” to be used as the root DOM element.

React elements are immutable i.e. once an element is created it is impossible to update its children or attribute. Thus to update an element, we must use the render() method.

React is chosen over the legacy of DOM updates because of its increased efficiency. It achieves this efficiency by using the virtual DOM and an efficient differentiating algorithm.

A component is one of the core building blocks of React they make the task of building UIs much easier. The UI is usually broken down into multiple individual pieces called components that can be worked on independently and merged into a parent component.

Components return a piece of JSX code that tells what should be rendered on the screen. In React we have two types of components:

  • Functional components: these are simply javascript functions that may or may not receive data as parameters.
  • Class components: we use Javascript ES6 classes to create class-based components in React and we can pass data from one class component to another.

We use functional components when we are sure that our component does not require interacting or working with other components.

The name of a component should always start with a capital letter. This is done to differentiate a component tag from an HTML tag.

Composing components entails merging all individual components to make a parent component.

Decomposing components means breaking down the component into smaller components.

It is recommended in React to break down a component into the smallest unit possible and then merge a parent component to increase the code modularity and reusability.

If we want to pass some data to our components React allows us to do so with the help of ************props(************which stands for properties). Props are objects which can be used inside a component.

We can pass props to any component as we declare attributes for any HTML tag.

// We are passing a prop named sampleProp to the component named
//DemoComponent which has the value "HelloProp"

<DemoComponent sampleProp = "HelloProp" />

We can access any props inside from the component’s class to which the props are pass is passed. The props can be accessed as shown below:

this.props.propName

The this. props is a global object which stores all of a component’s props. The propName is the name of the props that are key to this object.

We will use both a class-based component and a function-based component to illustrate the props.

Class based component

import React from 'react';
import ReactDOM from 'react-dom';

// sample component to illustrate props
class DemoComponent extends React. Component{
render(){
return(
<div>
{/*accessing information from props */}
<h2>Hello {this.props.user}</h2>
<h3>Welcome to GeeksforGeeks</h3>
</div>
);
}
}

Function-based component

import React from 'react';
import ReactDOM from 'react-dom';

// functional component to illustrate props
function DemoComponent(props){
return(
<div>
{/*accessing information from props */}
<h2>Hello {props.user}</h2>
<h3>Welcome to GeeksforGeeks</h3>
</div>
);
}

To pass information from one component to another using a class-based component looks like this:

import React from 'react';
import ReactDOM from 'react-dom';

// Parent Component
class Parent extends React. Component{
render(){
return(
<div>
<h2>You are inside Parent Component</h2>
<Child name="User" userId = "5555"/>
</div>
);
}
}

// Child Component
class Child extends React. Component{
render(){
return(
<div>
<h2>Hello, {this.props.name}</h2>
<h3>You are inside Child Component</h3>
<h3>Your user id is: {this.props.userId}</h3>
</div>
);
}
}

Props are read-only we are not allowed to modify the content of a prop. Whatever the type of component whether functional or class-based none of them is allowed to modify their props.

If we wanted to pass some default information using props to our components. React allows us to do so by providing us with something called defaultProps. This is a method that we can use to store as much information as we want for a particular class. This information can be accessed from anywhere inside that particular class every piece of information you add inside the defaultProps will be added as the prop of that class.

import React from 'react';
import ReactDOM from 'react-dom';

// Component
class ExampleClass extends React.Component {
render() {
return (
<div>
{/* using default prop - title */}
<h1>This is {this.props.title}'s Website!</h1>
</div>
);
}
}

// Creating default props for
// ExampleClass Component
ExampleClass.defaultProps = {
title: "GeeksforGeeks"
}

ReactDOM.render(
<ExampleClass />,
document.getElementById("root")
);

You can also pass arrays as props instead of passing single elements. In the program belowe we are iterating over the array passed to the components ExampleClass using map()

import React from 'react';
import ReactDOM from 'react-dom';

// Component
class ExampleClass extends React.Component {
render() {
return (
<div>
{/* iterating over array using map() */}
<h1>{this.props.names.map(
function namesIterator(item, i) {
return (
"Student " + (i + 1) + ": " +
item +
((i != 2) ? ', ' : '\\n')
)
}

)}</h1>
</div>
);
}
}

// Passing an array as prop
ExampleClass.defaultProps = {
names: ['Ram', 'Shyam', 'Raghav']
}

ReactDOM.render(
<ExampleClass />,
document.getElementById("root")
);

It is seen that functional components are faster and much simpler than class components. The primary difference between the two is the availability of the state.

The state of a component is an object that holds some information that may change over the lifetime of the component.

Differences between state and props.

  1. Props are immutable i.e. once set the props cannot be changed, while state is an observable object that is used to hold data that may change over time and to control the behavior after each change.
  2. States can be used in class components, and functional components with the use of React Hooks(useState and other methods) while props don’t have this limitation.
  3. While props are set by the parent component, the state is generally updated by event handlers.

Conventions of using State in React

  • The state of a component should prevail throughout its lifetime, thus we must first have some initial state to do so we define the state in the constructor of the component’s class. To define the state of any class we can use the sample format below
Class MyClass extends React.Component {
constructor(props) {
super(props);
this.state = { attribute : "value" };
}
}
  • The state should never be updated explicitly: React uses an observable object as the state that observes what changes are made to the state and helps the component behave accordingly. e.g if we update the state of any component like the following, the webpage will not re-render itself because React State will not be able to detect the changes made.
this.state.attribute = "new-value";
  • Thus React provides its own method setState() which is a method that takes a single parameter and expects an object which should contain the set of values to be updated. Once the update is done the method implicitly calls the render() method to repaint the page. Hence, the correct method of updating the value of a state will be similar to the code below:
this.setState({attribute: "new-value"});
  • The only time we are allowed to define the state explicitly is in the constructor to provide the initial state.
  • React is highly efficient and thus uses asynchronous state updates i.e. React may update multiple setState() updates in a single go. Thus using the value of the current state may not always generate the desired result. To counter this we use the arrow function format to take the previous state and props of the component as parameters. This can be written using the default functional way as follows:
this.setState((prevState, props) => ({
counter: prevState.count + props.diff
}));
  • State updates are independent: The state object of a component may contain multiple attributes and React allows to use setState() function to update only a subset of those attributes as well as using multiple setState() methods to update each value independently

React lifecycle of components.

The lifecycle of a component can be defined as the series of methods that are invoked in different stages of the component’s existence. A react component can go through four stages of its life as follows:

  1. Initialization: This is where the component is constructed with the given props and default state.
  2. Mounting: This is the stage of rendering the JSX returned by the render method itself.
  3. Updating: This is when the state of a component is updated and the application is repainted.
  4. Unmounting: The final step of the component lifecycle where the component is removed from the page.

React provides the developers with a set of predefined functions that id present are invoked around specific events in the lifetime of the component. Developers are supposed to override the functions with desired logic to execute accordingly.

Functions of each Phase of the LIfecycle

  1. Initialization: Here we defined the props and initial state of the component.
  2. Mounting: this is the phase of the lifecycle when the initialization of the component is completed and the component is mounted on the DOM and rendered for the first time on the webpage. The mounting phase consists of two such predefined functions
  • componentWillMount() Function: this function is invoked right before the component is mounted on the DOM.
  • componentDidMount() function: is invoked right after the component is mounted in the DOM.

3.Updation: is the phase where the states and props of a component are updated as followed by some user events such as clicking, pressing a key on the keyboard

The following are the functions invoked at different points of the updation phase

  • componentWillReceuveProps() Function: This is a props-exclusive function and is independent of the state. This function is invoked before a mounted component gets its props reassigned. The function is passed the new set of props which may or may not be identical to the original props.
  • setState() function: this is not particularly a lifecycle function and can be invoked explicitly at any instant. This function is used to update the state of a component.
  • shouldComponentUpdateFunction(): by default, every state or props update re-renders the page but this may not always be considered the desired outcome sometimes it is desired that updating the page is not required. This function fulfills the requirement by letting React know whether the component’s output will be affected by the update or not. shouldComponentUpdate() is invoked before rendering an already mounted component when new props or states are received. If returned false then the subsequent steps of rendering will not be carried out.
  • componentWillUpdate()function: is invoked after the component is rerendered i.e. this function gets invoked once the render() function is executed after the updation of state or props.
  • componentDidUpdate() function: is invoked after the component is rerendered i.e. this function gets invoked once the render()function is executed after the updation of state or props.
  1. Unmounting: this is the final phase of the lifecycle of the component which is the phase of unmounting the component from the DOM. The componentWillUnmount() function is the sole member of this phase.

componentWillUnmount() function is invoked before the component is finally unmounted from the DOM i.e. it gets invoked once before the component is removed from the page and this denotes the end of the lifecycle.

Conditional rendering is used to create multiple components and render them based on conditions.

We use the logical && operator along with some conditions to decide what will appear in the output based on whether the condition evaluates to true or false. Below is the syntax of using the logical && operator with conditions:

{
condition &&

// This section will contain
// elements you want to return
// that will be a part of output
}

If the condition provided in the above syntax evaluates to True then the elements right after the && operator will be a part of the output and if the condition evaluates to false then the code within the curly braces will not appear in the output.

Sometimes we may not want some components to render. To prevent a component from rendering we will have to return null as its rendering output

To create a list of elements in React we pass that list to a component using props and then use this component to render the list to the DOM. Each of the list items must have a unique “key”.

import React from 'react';
import ReactDOM from 'react-dom';

// Component that will return an
// unordered list
function Navmenu(props)
{
const list = props.menuitems;

const updatedList = list.map((listItems)=>{
return(
<li key={listItems.toString()}>
{listItems}
</li>
);
});

return(
<ul>{updatedList}</ul>
);
}

const menuItems = [1,2,3,4,5];

A key is a special string attribute you need to include when creating lists of elements in React. Keys are used in React to identify which items in the list are changed, updated, or deleted.

It is recommended to use a string as a key that uniquely identifies the items in the list. e,g

const numbers = [1, 2, 3, 4, 5];

const updatedNums = numbers.map((number) => {
return <li key={index}>{number} </li>;
});

You can also assign the array indexes as keys to the list items however this is highly discouraged because if the elements of the arrays get reordered in the future then it will get confusing for the developer as the keys for the elements will also change.

All elements in a particular array should have unique keys hence two different arrays can have the same set of keys.

Keys are not the same as props, only the method of assigning a” key” to a component is the same as that of props. Keys are internal to React and can not be accessed from insde of the component like props. Therefore we cannot use the same value we have assigned to the Key for any other prop we are passing to the component.

React uses forms to interact with the user and provides additional functionality such as preventing the default behavior of the form which refreshes the browser after the form is submitted.

Whatever value a user types we save it in state and pass the same value to the input tag as its value, so here DOM does not change its value, it is controlled by React state. To do this we use controlled components.

0

0

0

The Passionate Programmer
I code that's my super power!!

More Articles

Showwcase is a professional tech network with over 0 users from over 150 countries. We assist tech professionals in showcasing their unique skills through dedicated profiles and connect them with top global companies for career opportunities.

© Copyright 2024. Showcase Creators Inc. All rights reserved.