ReactJS
What is React JS?
React is an open-source component-based front-end JavaScript library. It is used to create fast and interactive user interfaces for web and mobile applications. It is easy to create a dynamic application in React because it requires less coding and offers more functionality. It is used by big MNCs and fresh new startups.
What I know about React JS
- Installation for ReactJS on Vscode
- Props
- Components
- Conditional Rendering
- Keys
Let’s go into details shall we:
PLEASE NOTE ALL CODES USED IN THIS ARTICLE WERE TAKEN FROM “GEEKSFORGEEKS” FOR EASIER UNDERSTANDING.
React installation on Vscode
Step 1:
Install Node.js
Before you start the React installation process, you must have Node.js installed on your computer. You have to install Node first because React.js is a JavaScript library, and Node.js is a JavaScript runtime environment that allows you to run JavaScript on the server side.
Step 2:
Install React
Now you can go ahead and install React into your project. Let’s go through the steps together.
First, we’ll look at the “traditional” way of installing React, using [create-react-app.]
In the command prompt window, create a folder that you will be using to create your React app. Type mkdir [folder name] then navigate to the newly created directory using cd [newly created folder name].
In the newly created folder directory, type in [npx create-react-app (project name of your choice)], and then wait until your React project is completely created.
Lastly, open the React project in your code editor by typing in [code.].
Props
In React, components can receive information from a parent component by utilizing props (short for properties). A prop is an object accessible to all React components. It serves as a means to pass data from a parent component to a child component.
Passing and Accessing props
We can pass props to any component as we declare attributes for any HTML tag.
Syntax:
// Passing Props
<DemoComponent sampleProp = “HelloProp” />
In the above code snippet, we are passing a prop named sampleProp to the component named DemoComponent. This prop has the value “HelloProp”. Let us now see how can we access these props.
We can access any props inside from the component’s class to which the props are passed.
Syntax:
// Accessing props
this.props.propName;
The ‘this.props’ is a kind of global object that stores all of a component’s props. The propName, that is the names of props are keys of this object.
Let us see an example where we will implement passing and accessing props.
In the below example, we will use a class-based component to illustrate the props. But we can also pass props to function-based components going to past in the below example.
To access a prop from a function we do not need to use the ‘this’ keyword anymore. Functional components accept props as parameters and can be accessed directly.
Example 1: Sample component to illustrate props
import React from ‘react’;
import ReactDOM from ‘react-dom/client’;
// 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 the React world!</h3>
</div>
);
}
}
const root = ReactDOM.createRoot(document.getElementById(“root”));
root.render(
<React.StrictMode>
<DemoComponent />
</React.StrictMode>
);
Example 2: Functional component to illustrate props
import React from ‘react’;
import ReactDOM from ‘react-dom/client’;
// functional component to illustrate props
function DemoComponent(props){
return(
<div>
{/*accessing information from props */}
<h2>Hello {props.user}</h2>
<h3>Welcome to the React World!</h3>
</div>
);
}
const root = ReactDOM.createRoot(document.getElementById(“root”));
root.render(
<React.StrictMode>
<DemoComponent user=”Geeks”/>
</React.StrictMode>
);
NB: Props are read-only. We are not allowed to modify the content of a prop. Whatever the type of Component is — functional or class-based, none of them is allowed to modify their props.
Components
In React, components serve as independent and reusable code blocks for UI elements. They represent different parts of a web page and contain both structure and behavior. They are similar to JavaScript functions and make creating and managing complex user interfaces easier by breaking them down into smaller, reusable pieces.
A Component is one of the core building blocks of React. They have the same purpose as JavaScript functions and return HTML. Components make the task of building UI much easier. You can work on components independently and then merge them all into a parent component which will be your final UI. Components promote efficiency and scalability in web development by allowing developers to compose, combine, and customize them as needed.
Types of Components in React
In React, we mainly have two types of components:
- Functional Components
- Class based Components
Functional Component
These are just like JavaScript functions that accept properties and return a React element. We can create a functional component in React by writing a JavaScript function. These functions may or may not receive data as parameters.
Functional Component Example:
Create a function component called welcome.
function welcome() {
return <h1>Hello, Welcome to the React world!</h1>;
}
Class Component
The class components are a little more complex than the functional components. A class component can show the inheritance and access data of other components.
Class Component must include the line “extends React.Component” to pass data from one class component to another. We can use JavaScript ES6 classes to create class-based components in React.
Class Component Example:
Create a class component called welcome.
class Welcome extends Component {
render() {
return <h1>Hello, Welcome to the React world!</h1>;
}
}
Difference between Functional Component and Class Component
A functional component is best suited for cases where the component doesn’t need to interact with other components or manage complex states. Functional components are ideal for presenting static UI elements or composing multiple simple components together under a single parent component.
While class-based components can achieve the same result, they are generally less efficient compared to functional components. Therefore, it’s recommended to not use class components for general use.
Conditional Rendering
React allows us to conditionally render components which means that the developer can decide which component to render on the screen based on some predefined conditions. This is known as conditional rendering.
Implementing Conditional Rendering
There may arise a situation when we want to render something based on some condition. For example, consider the situation of handling a login/logout button. Both the buttons have different functions so they will be separate components. Now, the task is if a user is logged in then we will have to render the Logout component to display the logout button and if the user is not logged in then we will have to render the Login component to display the login button.
Get Tochukwu Mezue’s stories in your inbox
Join Medium for free to get updates from this writer.
Conditional rendering in React can be implemented in three ways:
Using if else Statement
Using Logical && Operator
- Conditional Rendering using if-else Statement
We can create two components and create a Boolean variable that decides the element to be rendered on the screen.
if-else Statement Example:
import React from “react”;
import ReactDOM from “react-dom”;
// Message Component
function Message(props)
{
if (props.isLoggedIn)
return <h1>Welcome User</h1>;
else
return <h1>Please Login</h1>;
}
// Login Component
function Login(props) {
return <button onClick={props.clickFunc}>Login</button>;
}
// Logout Component
function Logout(props) {
return <button onClick={props.clickFunc}>Logout</button>;
}
// Parent Homepage Component
class Homepage extends React.Component {
constructor(props) {
super(props);
this.state = { isLoggedIn: false };
this.ifLoginClicked = this.ifLoginClicked.bind(this);
this.ifLogoutClicked = this.ifLogoutClicked.bind(this);
}
ifLoginClicked() {
this.setState({ isLoggedIn: true });
}
ifLogoutClicked() {
this.setState({ isLoggedIn: false });
}
render() {
return (
<div>
<Message isLoggedIn={this.state.isLoggedIn} />
{this.state.isLoggedIn ? (
<Logout clickFunc={this.ifLogoutClicked} />
) : (
<Login clickFunc={this.ifLoginClicked} />
)}
</div>
);
}
}
ReactDOM.render(<Homepage />, document.getElementById(“root”));
Explanation:
In the above output, you can see that on clicking the Login button the message and button get changed and vice versa.
2. Conditional Rendering using logical && operator
We can use the logical && operator along with some conditions to decide what will appear in output based on whether the condition evaluates to true or false.
logical && operator Example:
import React from ‘react’;
import ReactDOM from ‘react-dom’;
// Example Component
function Example(){
const counter = 5;
return(<div>
{
(counter==5) &&
<h1>Hello World!</h1>
}
</div>
);
}
ReactDOM.render(
<Example />,
document.getElementById(‘root’)
);
Explanation:
In the above output, You can see that since the condition (counter == 5) evaluates to true the <h1> element is successfully rendered on the screen.
React Keys
React JS keys are a way of providing a unique identity to each item while creating the React JS Lists so that React can identify the element to be processed. 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. Keys are used to give an identity to the elements in the lists. It is recommended to use a string as a key that uniquely identifies the items in the list.
Assigning keys to the list
You can assign the array indexes as keys to the list items. The below example assigns array indexes as keys to the elements.
Syntax:
const numbers = [1, 2, 3, 4, 5];
const updatedNums = numbers.map((number, index) =>
<li key={index}>
{number}
</li>
);
The issue with index as keys
Assigning indexes as keys 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.
Using Keys with Components :
Consider a situation where you have created a separate component for list items and you are extracting list items from that component. In that case, you will have to assign keys to the component you are returning from the iterator and not to the list items. That is you should assign keys to <Component /> and not to <li> A good practice to avoid mistakes is to keep in mind that anything you are returning from inside of the map() function is needed to be assigned a key.
Correct usage of keys:
The below example shows the correct usage of keys.
import React from “react”;
import ReactDOM from “react-dom”;
// Component to be extracted
function MenuItems(props) {
const item = props.item;
return <li>{item}</li>;
}
// Component that will return an unordered list
function Navmenu(props) {
const list = props.menuitems;
const updatedList = list.map((listItems) => {
return <MenuItems key={listItems.toString()} item={listItems} />;
});
return <ul>{updatedList}</ul>;
}
const menuItems = [1, 2, 3, 4, 5];
ReactDOM.render(
<Navmenu menuitems={menuItems} />,
document.getElementById(“root”)
);
Output: In the output, you can see that the output is rendered but without any type of warning in the console, it is the correct way to use React Keys.
Incorrect usage of keys:
The below code shows the incorrect usage of keys:
import React from “react”;
import ReactDOM from “react-dom/client”;
// Component to be extracted
function MenuItems(props) {
const item = props.item;
return <li key={item.toString()}>{item}</li>;
}
// Component that will return an unordered list
function Navmenu(props) {
const list = props.menuitems;
const updatedList = list.map((listItems) => {
return <MenuItems item={listItems} />;
});
return <ul>{updatedList}</ul>;
}const menuItems = [1, 2, 3, 4, 5];
const root = ReactDOM.createRoot(document.getElementById(‘root’));
root.render(
<React.StrictMode>
<Navmenu menuitems={menuItems} />
</React.StrictMode>
);
Output: You can see in the output that this time the list is rendered successfully but a warning is thrown to the console that the elements inside the iterator are not assigned keys. This is because we had not assigned the key to the elements we are returning to the map() iterator.
Uniqueness of Keys:
We have told many times while discussing keys that keys assigned to the array elements must be unique. By this, we did not mean the keys should be globally unique. All the elements in a particular array should have unique keys. That is, two different arrays can have the same set of keys.
Example: In the below code, we have created two different arrays menuItems1 and menuItems2.
import React from “react”;
import ReactDOM from “react-dom”;
// Component to be extracted
function MenuItems(props) {
const item = props.item;
return <li>{item}</li>;
}
// Component that will return an unordered list
function Navmenu(props) {
const list = props.menuitems;
const updatedList = list.map((listItems) => {
return <MenuItems key={listItems.toString()} item={listItems} />;
});
return <ul>{updatedList}</ul>;
}
const menuItems1 = [1, 2, 3, 4, 5];
const menuItems2 = [1, 2, 3, 4, 5, 6];
ReactDOM.render(
<div>
<Navmenu menuitems={menuItems1} />
<Navmenu menuitems={menuItems2} />
</div>,
document.getElementById(“root”)
);
Output: You can see in the output the keys for the first 5 items for both arrays are the same still the code runs successfully without any warning.
Difference between keys and props in React
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 inside the component like props. Therefore, we can use the same value we have assigned to the Key for any other prop we are passing to the Component.
Features of React:
Reusable Components: A single React app consists of many components each component has its logic and code but we can easily reuse components any number of times hence reducing the developer’s time and increasing the efficiency of work
Debugging: React app can be easily debugged using “react developer tools". It’s a browser extension that can be used for both Chrome as well as Firefox.
My Understanding of React JS
What made sense to me in React Js are these two concepts:
- Conditional Rendering
- Keys
My understanding of conditional Rendering
Conditional rendering is a versatile technique in web development for dynamically displaying content based on various conditions, enabling the creation of interactive and responsive user interfaces.
From what I understand about Conditional Rendering these are what it entails:
Data-Driven Rendering: Often, conditional rendering is driven by data or state changes in an application. Based on the current state of the application, certain components or elements are rendered or hidden.
Dynamic UI: Conditional rendering allows for the creation of dynamic user interfaces where the content displayed can change based on user interactions, data updates, or other events.
Component-Level Rendering: Conditional rendering can occur at different levels of granularity, from entire components to individual elements within a component. This allows for fine-grained control over the appearance and behavior of the UI.
Error Handling: Conditional rendering is commonly used for error handling in applications. For example, if an API request fails, an error message can be conditionally rendered to inform the user of the problem.
Performance Considerations: While conditional rendering is a powerful technique, it’s important to consider performance implications, especially in large applications with complex UI logic. Excessive conditional rendering can lead to slower rendering times and decreased performance.
My understanding of Keys
keys play a crucial role in optimizing the performance and rendering behavior of React applications, particularly when dealing with dynamically generated or updated lists of elements. By providing stable identities to elements, keys enable React to efficiently update the UI and minimize unnecessary re-renders.
From what I understand about Keys these are what it entails:
Unique Identifier: Keys are used to give React a hint about which elements can be reused, added, or removed. They must be unique among siblings but don’t necessarily have to be globally unique.
Optimizing Reconciliation: React uses keys during the process of reconciliation (the algorithm it uses to efficiently update the UI). Keys help React identify which items have changed, are added, or are removed from a list, allowing it to re-render only the necessary components instead of re-rendering the entire list.
Stable Identity: Keys provide a stable identity to elements across renders. This is particularly important when dealing with lists that are dynamically generated or updated based on some data source.
Performance Benefits: Properly using keys can lead to performance improvements, especially when working with large lists. React can efficiently update the DOM by reordering, adding, or removing elements based on the changes detected through keys.
Avoiding Key Conflicts: Keys should be stable, predictable, and consistent. Avoid using random values as keys, as they can lead to unnecessary re-renders or key conflicts when elements are moved or reordered.
Dynamic Key Generation: Keys can be dynamically generated based on the item’s properties or some unique identifier associated with the item. This ensures that the keys remain unique and stable across renders.










