Showing posts with label React. Show all posts
Showing posts with label React. Show all posts

Thursday, June 27, 2024

State management in React component

In React, there are two types of components: class components and functional components. Until React introduced hooks, only class components could manage state using this.state. However, with the introduction of hooks, functional components can now also manage state using the useState hook.

Functional component:
Here's an example of a functional component using state with the useState hook:
import React, { useState } from 'react';

function MyComponent() {
  const [count, setCount] = useState(0);

  const incrementCount = () => {
    setCount(count + 1);
  };

  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={incrementCount}>Increment</button>
    </div>
  );
}

export default MyComponent;
In this functional component, useState hook is used to declare a state variable count and a function setCount to update its value. However, if you're using class components, managing state with this.state is still a valid and commonly used approach. Note that useState returns an array of two elements which is destructured and stored in count and setCount. The useState receives initial state as parameter. In the above example, count is 0 which can be updated by setCount function.

Class component:
In class components in React, initializing the state using this.state is the standard and recommended approach. In React class components, the state should always be initialized in the constructor using this.state. This is because React relies on this.state to manage and update component state efficiently.

Here's the typical way to initialize state in a React class component:
import React, { Component } from 'react';

class MyComponent extends Component {
  constructor(props) {
    super(props);
    this.state = {
      count: 0
    };
  }

  render() {
    return (
      <div>
        <p>Count: {this.state.count}</p>
        <button onClick={() => this.setState({ count: this.state.count + 1 })}>
          Increment
        </button>
      </div>
    );
  }
}

export default MyComponent;
In this example, this.state is used to initialize the component's state in the constructor. This is the standard approach and is recommended in case of class component.

Life cycle of React component

In React, the lifecycle of a class component can be divided into three main phases: mounting, updating, and unmounting.

1. Mounting: This phase occurs when an instance of a component is being created and inserted into the DOM. The lifecycle methods involved in this phase are:
  • constructor(): This is called before the component is mounted. It's where you initialize state and bind event handlers.
  • render(): This method is mandatory and it returns the JSX that represents the component.
  • componentDidMount(): This method is called after the component has been rendered into the DOM. It's often used for fetching data from APIs or setting up subscriptions.
2. Updating: This phase occurs when a component is being re-rendered as a result of changes to either its props or state. The lifecycle methods involved in this phase are:
  • shouldComponentUpdate(): This method is called before rendering when new props or state are being received. It allows you to control whether the component should re-render or not by returning a boolean value.
  • render(): Again, this method is called to re-render the component with the updated state and props.
  • componentDidUpdate(): This method is called after the component's updates are flushed to the DOM. It's often used to perform DOM operations or to fetch new data based on changes.
3. Unmounting: This phase occurs when a component is being removed from the DOM. The lifecycle method involved in this phase is:
  • componentWillUnmount(): This method is called immediately before a component is unmounted and destroyed. It's often used to clean up any DOM elements or subscriptions set up in componentDidMount().
Note:
Additionally, there are other less commonly used lifecycle methods like getDerivedStateFromProps(), getSnapshotBeforeUpdate(), componentDidCatch(), and static getDerivedStateFromError() which are used for more specific use cases like error boundaries and controlling state updates.

Is life cycle of function components possible?

Function components in React don't have lifecycle methods like class components do. However, with the introduction of React Hooks, function components can achieve similar behavior.
  • Effect Hook (useEffect): This hook replaces lifecycle methods like componentDidMount, componentDidUpdate, and componentWillUnmount. You can perform side effects such as data fetching, subscriptions, or manually changing the DOM inside a function component using useEffect.
  • State Hook (useState): This hook allows function components to have local state, similar to how this.state works in class components.
  • Context Hook (useContext): This hook allows function components to consume context values created by React.createContext.
  • Ref Hook (useRef): This hook allows function components to keep track of mutable values that persist across renders, similar to instance variables in class components.
Using these hooks, function components can achieve the same behavior as class components with lifecycle methods. Additionally, they provide a more concise and readable way to manage component logic.

React Library or Framework

The terms 'library' and 'framework' are often used interchangeably, but they have distinct meanings in the context of software development:

1. Library:
  • A library is a collection of reusable code modules or functions that can be directly called by an application to perform specific tasks.
  • Libraries typically provide functionality for a specific purpose, such as parsing JSON data, handling networking, or rendering user interfaces.
  • When using a library, the control flow of the application remains with the developer. The developer decides when and how to use the functions provided by the library.
2. Framework:
  • A framework, on the other hand, provides a structure or skeleton for an entire application. It defines the architecture, design patterns, and flow of control for the application.
  • Developers build their applications within the framework by providing implementation details for various components or by extending the framework's functionality.
  • In contrast to libraries, where the developer calls the library code, in a framework, the flow of control is often inverted. The framework calls the developer's code at specific points, following a predefined structure.
React is a library
React is commonly referred to as a JavaScript library for building user interfaces. Reasons are as follows:
  1. React provides a collection of reusable UI components that developers can use to build their interfaces. It's focused on rendering user interfaces and managing the state of those interfaces efficiently.
  2. React does not dictate the entire structure or architecture of an application. While it offers guidance on how components should be structured and managed, it doesn't enforce a rigid application structure or control flow.
  3. Developers maintain control over how they structure their applications, how they manage application state, and how they integrate React into their overall architecture. React doesn't impose strict control over these aspects, which is more characteristic of a library than a framework.
In summary, React focuses on UI rendering, its lack of strict control over application structure, and its emphasis on component reusability make it more akin to a library rather than a full-fledged framework.

React App.js file

When you setup React project, App.js file is created by create-react-app in src folder. In a React project, the 'App.js' file typically serves as the main component of your application. It's where you define the structure and behavior of your application's top-level UI. Here's how the 'App.js' file is commonly used:

1. Define the Root Component: The 'App.js' file usually defines the root component of your application. This component represents the overall structure of your application and may contain other components as its children.

2. Import Necessary Dependencies: You may need to import additional dependencies, such as React components, CSS files, or other resources, depending on your application's requirements.

3. Define the App Component: Inside the 'App.js' file, you define the 'App' component using JavaScript syntax. This component can be a functional component or a class component, depending on your preference and needs.

4. Implement the Component's Structure: Within the 'App' component, you define the structure of your application's UI using JSX (JavaScript XML). JSX allows you to write HTML-like code directly within your JavaScript files, making it easier to create and manage UI components.

5. Include Other Components: You can include other React components within the 'App' component to compose the overall UI of your application. These components may represent different sections, features, or views of your application.

6. Export the App Component: Finally, you export the 'App' component so that it can be imported and used in other parts of your application or by other components.

Here's a simple example of what the 'App.js' file might look like:
import logo from './logo.svg';
import './App.css';

function App() {
  return (
    <div className="App">
      <header className="App-header">
        <img src={logo} className="App-logo" alt="logo" />
        <p>
          Edit <code>src/App.js</code> and save to reload.
        </p>
        <a
          className="App-link"
          href="https://reactjs.org"
          target="_blank"
          rel="noopener noreferrer"
        >
          Learn React
        </a>
      </header>
    </div>
    <main>
    {/* Other components or content */}
    </main>
    <footer>
    {/* Footer content */}
    </footer>
  );
}

export default App;
In this example, the 'App' component represents the overall structure of the application, including a header, main content area, and footer. It also imports a CSS file ('App.css') to apply styles to the component. Finally, the 'App' component is exported as the default export so that it can be used elsewhere in the application.

React JS PropTypes with Class Component

PropTypes is a library in React used to validate the props that are passed to a component. Props (short for properties) are used to pass data from one component to another in React. PropTypes help ensure that the components receive the props they expect, which can help catch bugs and make the code more readable and maintainable.

How can we use PropTypes with Class Component?

To use PropTypes with class components in React, you can define a static property called 'propTypes' on your class component. Here's how you can do it:

1. First, install the 'prop-types' package if you haven't already:

npm install prop-types

2. Import PropTypes in your class component file:

import PropTypes from 'prop-types';

3. Define the 'propTypes' static property on your class component and specify the expected types for each prop:

   import React, { Component } from 'react';
   import PropTypes from 'prop-types';

   class MyComponent extends Component {
     render() {
       return <div>{this.props.message}</div>;
     }
   }

   MyComponent.propTypes = {
     message: PropTypes.string.isRequired,
   };

In this example, we're using PropTypes to specify that the 'message' prop should be a string and is required ('isRequired'). PropTypes will issue a warning in the console if the expected prop types are not provided or do not match the specified types.

Look at another example:

function MyComponent({ name, age, isActive }) {
  return (
    <div>
      <h1>{name}</h1>
      <p>Age: {age}</p>
      <p>{isActive ? "Active" : "Inactive"}</p>
    </div>
  );
}

MyComponent.propTypes = {
  name: PropTypes.string.isRequired,
  age: PropTypes.number.isRequired,
  isActive: PropTypes.bool,
};

MyComponent.defaultProps = {
  isActive: false,
}; 

Explanation:

  • PropTypes.string.isRequired: This means the name prop should be a string and is required.
  • PropTypes.number.isRequired: This means the age prop should be a number and is required.
  • PropTypes.bool: This means the isActive prop should be a boolean and is optional.
  • defaultProps: This provides default values for props that are not passed by the parent component.

Common PropTypes Validators:

  1. PropTypes.any: The prop can be of any data type.
  2. PropTypes.bool: The prop should be a boolean.
  3. PropTypes.number: The prop should be a number.
  4. PropTypes.string: The prop should be a string.
  5. PropTypes.func: The prop should be a function.
  6. PropTypes.array: The prop should be an array.
  7. PropTypes.object: The prop should be an object.
  8. PropTypes.node: The prop can be any renderable node.
  9. PropTypes.element: The prop should be a React element.
  10. PropTypes.instanceOf: The prop should be an instance of a particular class.
  11. PropTypes.oneOf: The prop should be one of the specified values.
  12. PropTypes.oneOfType: The prop should be one of the specified types.
  13. PropTypes.arrayOf: The prop should be an array of a certain type.
  14. PropTypes.objectOf: The prop should be an object with property values of a certain type.
  15. PropTypes.shape: The prop should be an object with a specific shape.
  16. PropTypes.exact: The prop should be an object with an exact shape.
  17. Using PropTypes is a good practice to ensure the robustness and reliability of your React components, especially as your application grows in complexity.

You can specify PropTypes for all types of props, including strings, numbers, booleans, arrays, objects, functions, and even custom shapes or instances of specific classes. PropTypes provide a way to catch errors early and ensure that components receive the correct props, helping you build more robust and maintainable React applications.

TypeScript

In React, PropTypes is used to validate component properties (props). But we can also use TypeScript for this. Both methods allow you to specify the expected types and, optionally, whether the props are required or have default values.

Now, we look at TypeScript to validate component properties (props):
1. Define an interface for your props:

interface MyComponentProps {
   name: string;
   age?: number;
   isAdmin?: boolean;
}

2. Create your component and specify the props using the defined interface:

const MyComponent: React.FC<MyComponentProps> = (props) => {
return <div>{props.name}</div>;
};

3. TypeScript will automatically check that the props passed to `MyComponent` match the defined interface.

Difference:

Both PropTypes and TypeScript provide a way to catch errors early and ensure that the components in your application receive the correct props. PropTypes is a runtime validation tool, while TypeScript is a static type checker that catches errors during development. Choose the one that best fits your project's requirements and preferences.

React JS props with Class Component

How can we use Props with Class Component?

In React, class components can receive data from their parent components using props. Here's how you can use props with class components:

1. Define Props in Class Component:

Inside your class component, you can access props using 'this.props'. Props are passed to the constructor as the first argument or directly accessed within class methods.

   import React, { Component } from 'react';

   class MyComponent extends Component {
     render() {
       return <div>{this.props.message}</div>;
     }
   }

2. Pass Props from Parent Component:

When rendering a class component, you can pass props to it as attributes.

   import React, { Component } from 'react';
   import MyComponent from './MyComponent';

   class ParentComponent extends Component {
     render() {
       return <MyComponent message="Hello, world!" />;
     }
   }

3. Access Props Inside Class Component:

Once props are passed, you can access them inside the class component using 'this.props'.

   import React, { Component } from 'react';

   class MyComponent extends Component {
     render() {
       return <div>{this.props.message}</div>;
     }
   }

In this example, 'this.props.message' will render "Hello, world!".

4. Default Props:

You can also define default values for props using the 'defaultProps' static property.

   import React, { Component } from 'react';

   class MyComponent extends Component {
     render() {
       return <div>{this.props.message}</div>;
     }
   }

   MyComponent.defaultProps = {
     message: 'Default message'
   };

If 'message' prop is not provided when using 'MyComponent', it will default to "Default message".

Using props with class components allows you to pass data down the component hierarchy and make your components more dynamic and reusable.

React JS How to create a component

How can I create a react component in React project?

To create a React component in your project, you typically follow these steps:

1. Decide on the Component's Purpose: Determine the purpose and functionality of the component you want to create. Is it a simple UI element, a container for other components, or something else?

2. Choose a Location: Decide where the component should reside within your project's directory structure. Typically, components are placed in the 'src/components' directory.

3. Create a New File: In your chosen location, create a new JavaScript file for your component. You can name the file based on the component's purpose, for example, 'Button.js'.

4. Write the Component Code: In the newly created file, write the code for your component. Here's a basic example of a functional component:

   // Button.js
   import React from 'react';

   const Button = ({ onClick, children }) => {
     return (
       <button onClick={onClick}>
         {children}
       </button>
     );
   };

   export default Button;
This example creates a simple button component that accepts an 'onClick' event handler and displays its children as the button's content.

5. Use the Component: You can now use your newly created component in other parts of your application. Import it into any file where you want to use it and include it in the JSX markup. For example, you can use Button component in App component:

   // App.js

   import React from 'react';
   import Button from './components/Button';

   const App = () => {
     const handleClick = () => {
       console.log('Button clicked!');
     };

     return (
       <div>
         <h1>Hello, React!</h1>
         <Button onClick={handleClick}>Click me</Button>
       </div>
     );
   };

   export default App;

In this example, the 'Button' component is imported and used within the 'App' component. That's it! You've created a React component in your project and integrated it into your application. You can continue to build on this component by adding props, state, and additional functionality as needed.

Nested components in React JS

In React, components are used in hierarchy. One component is nested inside another and there is parent child relationship between them. Still, we have two types of components in React:

  1. Independent components and 
  2. Dependent components 

The difference lies in how they are defined and not how they are consumed. Because when a component is used then they have hierarchical relationship except for the top level container element which is usually DIV or a React fragment. This top level element is not React component.

In this post, you will see

  1. first, how one component can be defined independent from any other component.
  2. second, how one component can be used inside another component.
  3. third, how one component can be defined inside another component. 

Let's look at examples to see how components are defined:

IndependentOne Component:

import React from 'react'

function IndependentOne() {
  return (
    <div>
      <h3>IndependentOne</h3>
    </div>
  )
}

export default IndependentOne

IndependentTwo Component:

import React from 'react'

function IndependentTwo() {
  return (
    <div>
      <h3>IndependentTwo</h3>
</div> ) } export default IndependentTwo
Now we use IndependentOne component inside IndependentTwo component. Note that both components are independent; any of them can be used into another one.
import React from 'react'
import IndependentOne from './IndependentOne'

function IndependentTwo() {
  return (
    <div>
      <h3>IndependentTwo</h3>
      <IndependentOne/>
    </div>
  )
}

export default IndependentTwo

This demonstrates how you can compose UI components by using one component inside another in React. It's a powerful feature that allows you to create complex UIs by combining simpler, reusable components.

Next question is, can we define one component inside another component?

The answer is yes. You can define a one component inside the another component. This is often referred to as a "nested" component. Here's an example:


import React from "react";

// Parent functional component
const ParentComponent = () => {
  // Child functional component defined inside the parent component
  const ChildComponent = () => {
    return <p>This is the child component</p>;
  };

  return (
    <div>
      <h1>This is the parent component</h1>
      {/* Using the ChildComponent inside the ParentComponent */}
      <ChildComponent />
    </div>
  );
};

export default ParentComponent;

In this example:

  • We define a 'ParentComponent' functional component.
  • Inside the 'ParentComponent', we define a 'ChildComponent' functional component.
  • We then render the 'ChildComponent' directly inside the 'ParentComponent''s JSX markup.
  • When the 'ParentComponent' is rendered, it will also render the 'ChildComponent' within it.

Important:

Defining a child component inside the parent component can be useful for encapsulating functionality or UI elements that are closely related to the parent component and don't need to be reused elsewhere. However, keep in mind that the child component will only be available within the scope of the parent component and cannot be accessed or used outside of it.

Another Example

Component1: A simple, independent component that renders a div with an <h3> tag.

import React from 'react'

const Component1 = () => {
  return (
    <div>
      <h3>Component1</h3>
    </div>
  )
}

export default Component1

Component2: Another independent component that renders a div with an <h3> tag.

import React from 'react'

const Component2 = () => {
  return (
    <div>
      <h3>Component2</h3>
    </div>
  )
}

export default Component2

Component3: This component renders its own content (an <h3> tag) and uses Component1 inside its JSX.

function Component3() {

  return (

    <div>

      <h3>Component3</h3>

      <Component1 /> {/* Nested Component */}

    </div>

  );

}

Component3 is an example of a Nested Component. Why?

In React, nesting occurs when one component renders another component within its JSX. Here, Component1 is nested within Component3 because it is rendered as part of Component3's output.

  1. Parent Component: Component3 is the parent component because it renders Component1.
  2. Child (Nested) Component: Component1 is the child (or nested) component because it is consumed/rendered within Component3.
  3. Component2 is not nested within Component3 because it is defined separately and not used or rendered inside Component3. It is just another standalone component.
  4. Component3 is an example of a nested component because it renders another component (Component1) within its JSX.

If you use Component3 somewhere else (e.g., in App), rendering Component3 will automatically include its child, Component1.

React class component

What is class component?

In React, a class component is a type of component that is defined using ES6 classes. Class components are used to create more complex components that need to manage state, use lifecycle methods, or handle other advanced features.

Here's an example of a class component in React:

import React from "react";
// Define a class component
class MyClassComponent extends React.Component {
  // Constructor method to initialize state
  constructor(props) {
    super(props);
    this.state = {
      count: 0,
    };
  }

  // Render method to define the component's UI
  render() {
    return (
      <div>
        <h1>Class Component Example</h1>
        <p>Count: {this.state.count}</p>
        <button onClick={this.incrementCount}>Increment</button>
      </div>
    );
  }

  // Method to handle incrementing count
  incrementCount = () => {
    this.setState((prevState) => ({
      count: prevState.count + 1,
    }));
  };
}

export default MyClassComponent;

In this above example: 

  • We define a class component named 'MyClassComponent' by extending the 'Component' class provided by React.
  • The class component contains a constructor method where the initial state ('count') is defined.
  • The 'render()' method defines the UI of the component using JSX.
  • Class component can manage its own state using the 'this.state' object.
  • Class component can also define methods that are used to handle events or perform other tasks.
  • In this example, we define a method ('incrementCount') to handle incrementing the count state when a button is clicked.

Class component is being used since its early versions and is still widely used in React applications. However, with the introduction of React Hooks in React 16.8, functional components with hooks have become a popular alternative to class components for managing state and other features.

Question: Is it true that class component must have render() method which returns JSX?

True. In a class component, the 'render()' method is required, and its body must contain a 'return' statement that returns JSX (JavaScript XML) to describe the UI of the component.

Here's a typical structure of a class component:

import React, { Component } from "react";

class MyClassComponent extends Component {
  render() {
    return <div>{/* JSX representing the UI of the component */}</div>;
  }
}

export default MyClassComponent;

In this example:

  • The 'MyClassComponent' class extends the 'Component' class provided by React.
  • The 'render()' method returns JSX that describes the UI of the component.
  • JSX elements can represent HTML-like syntax and React components, allowing you to define the structure and appearance of your component.

The 'render()' method is a fundamental part of class components in React, as it determines what gets rendered to the DOM when the component is used. Without the 'render()' method, the component would not be able to render any content.

Question: In class component, if props is not needed, then constructor may not be required. Is it True or false?
Answer: False. In a class component, a constructor and props are not related. Constructor is to initialize the state of the component.

If a class component doesn't need to initialize state or perform any other setup using props, you can omit the constructor entirely. React will automatically create a default constructor for you if one is not explicitly defined.

Here's an example of a class component without a constructor:


import React, { Component } from "react";

class MyClassComponent extends Component {
  render() {
    return <div>{/* JSX representing the UI of the component */}</div>;
  }
}

export default MyClassComponent;

In this example, the 'MyClassComponent' class doesn't have a constructor, but it's still a valid class component in React. It inherits the default constructor provided by the 'Component' class.

When is constructor needed?

You only need to define a constructor in a class component if you need to perform specific initialization tasks, such as setting initial state, binding event handlers, or performing other setup operations. If you don't have any such requirements, you can omit the constructor altogether.

How can I set up the initial state of the class component?

In a class component in React, you can set up the initial state by defining a constructor method and initializing the state within it. Here's how you can do it:

import React, { Component } from "react";

class MyClassComponent extends Component {
  constructor(props) {
    super(props);
    this.state = {
      // Initial state values
      count: 0,
      name: "John",
    };
  }

  render() {
    return (
      <div>
        <p>Count: {this.state.count}</p>
        <p>Name: {this.state.name}</p>
      </div>
    );
  }
}

export default MyClassComponent;

In this example:

  • We define a 'constructor' method within the class component. This method is automatically called when an instance of the component is created.
  • Inside the constructor, we call 'super(props)' to call the constructor of the parent class (i.e., 'Component'). This is required in React class components when defining a constructor.
  • We initialize the 'state' object within the constructor, setting initial values for different state properties. In this example, we set the initial 'count' to '0' and the initial 'name' to ''John''.
  • We can then access the state properties ('this.state.count' and 'this.state.name') within the 'render()' method to display them in the UI.

This is the typical way to set up the initial state of a class component in React. The state can then be updated using 'setState()' method when needed, triggering a re-render of the component with the updated state values.

How EventHandler is used in Class Component?
In a class component in React, event handlers are typically defined as methods within the class. These methods are then passed as props to the JSX elements to handle specific events, such as clicks, changes, or submissions.

Here's how you can use event handlers in a class component:


import React, { Component } from "react";
class MyClassComponent extends Component {
  constructor(props) {
    super(props);
    this.state = {
      count: 0,
    };
  }

  // Event handler method to handle button click
  handleClick = () => {
    this.setState((prevState) => ({
      count: prevState.count + 1,
    }));
  };

  render() {
    return (

Count: {this.state.count}

{/* Button with onClick event handler */}
); } } export default MyClassComponent;

In this example:

  • We define a method named 'handleClick' within the class component. This method is used to handle the click event of a button.
  • Inside the 'handleClick' method, we call 'setState()' to update the 'count' state by incrementing its value.
  • In the 'render()' method, we include a button element with an 'onClick' attribute set to '{this.handleClick}'. This means that when the button is clicked, the 'handleClick' method will be called.
  • When the button is clicked, React will invoke the 'handleClick' method, which updates the state by incrementing the 'count' value. This triggers a re-render of the component with the updated state, causing the UI to reflect the new count value.

Functional component in React JS

Functional components are JavaScript functions that accept props as an argument and return React elements. The props are optional. You first of all look at the simplest example of functional component.
Example:
import React from 'react'

const MyFunComponent = () => {
  return (
    <div>
      <h2>I am Functional component</h2>
    </div>
  )
}

export default MyFunComponent
In this example, JavaScript function returns React element using JSX. Note that return statement must return a single React element; although the element may have any number of child React elements. In the example, the component returns 'div' element which has 'h2' as child element. We have used arrow function to represent Functional component; we can also use function declaration for the same as given below.
import React from 'react'

function MyFunComponent() {
  return (
    <div>
      <h2>I am Functional component</h2>
    </div>
  )
}

export default MyFunComponent

Reusable: 

As a component is a reusable piece of code, we can use it one or more times in any other component. In the below example, we use MyFunComponent component inside App component. Note that we have used import statement to use MyFunComponent component inside App component.

import React from "react";
import MyFunComponent from "./MyFunComponent";
const App = () => {
  return (
    <div>
      <h1>Hello React App</h1>
      <MyFunComponent />
      <MyFunComponent />
    </div>
  );
};

export default App;

Props:

Till now, we have used simple examples of functional component. Now we will use props in the component. Props is used to pass read-only data from one component to another component. It means that props data cannot be modified in the component. We can pass several data to a component via props. In fact, props is an object that holds several key-value pairs data. Passing data from one component to another component is based on parent and child relationship. To look at how one function component is used inside another function component, click this page link.

In case of functional component, props is passed as an argument of the functional component. Look at the following example.

Component receiving props:

import React from 'react'

function MyFunComponent(props) {
  return (
    <div>
      <h2>I am Functional component which receives name: {props.name}</h2>
      <h2>I am Functional component which receives age: {props.age}</h2>
    </div>
  )
}

export default MyFunComponent

Component passing props:

import React from "react";
import MyFunComponent from "./MyFunComponent";
const App = () => {
  return (
    <div>
      <h1>Hello React App</h1>
      <MyFunComponent name='appliedk'  age='20'/>
    </div>
  );
};

export default App;

How to declare and use variables in function component:

In a function component in React, you can declare variables using the 'const' or 'let' keywords within the function body, just like in regular JavaScript. Once declared, these variables can be used within the function component. Here's an example:

import React from 'react';

const MyComponent = () => {
  // Declare a variable
  const name = 'John';

  // Use the variable in JSX
  return (
    <div>
      <p>Hello, {name}!</p>
    </div>
  );
};

export default MyComponent;

In this example:

  • We declare a variable named 'name' using the 'const' keyword within the 'MyComponent' function component.
  • We use the 'name' variable directly within the JSX markup, using curly braces '{}' to embed the JavaScript expression.

Variables declared within a function component are scoped to that component and cannot be accessed outside of it. They are typically used to store values that are specific to the component and are not shared with other components.

Event Handler in a function component

In a function component in React, you can declare event handlers as regular functions within the component body. Once declared, you can pass these event handler functions as props to JSX elements to handle specific events. Here's an example:

import React from 'react';

const MyComponent = () => {
  // Event handler function
  const handleClick = () => {
    console.log('Button clicked!');
  };

  // Use the event handler function in JSX
  return (
    <div>
      {/* Button with onClick event handler */}
      <button onClick={handleClick}>Click me</button>
    </div>
  );
};

export default MyComponent; 

In this example:

  • We declare an event handler function named 'handleClick' using a regular function syntax within the 'MyComponent' function component.
  • We use the 'handleClick' function as the value of the 'onClick' attribute in the JSX button element. This means that when the button is clicked, the 'handleClick' function will be called.
  • Inside the 'handleClick' function, we log a message to the console indicating that the button was clicked.

Event handler functions in function components work similarly to event handler methods in class components. They are invoked when the corresponding event occurs, allowing you to perform actions or update state in response to user interactions.

Types of React components

What is React component?
A React component is a fundamental building block of a React application. It encapsulates a piece of the user interface (UI) that can be reused, composed, and maintained independently. It is a self-contained unit of code that defines a part of the user interface. Components can be simple or complex and are written using JavaScript along with JSX (JavaScript XML), which allows you to write HTML-like syntax within your JavaScript code. Eventually, JSX is translated into JavaScript code by Babel transpiler. 

JSX allows you to write HTML-like XML code within JavaScript. JSX is XML based code because it expects XML like well defined tags. You will learn about JSX in separate post. React component can be written without using JSX but as JSX simplifies development of React application, it must be used.

React components can be thought of as custom, reusable HTML elements, which can accept inputs (called "props") and maintain internal state.

Types of React Components

There are mainly two types of React components which are as follows:

  1. Class component
  2. Functional component

Class Components
Definition: These are ES6 classes that extend React.Component and must define a render method that returns React elements.

Example1:

import React from 'react'
export default class MyComponent extends React.Component {
  render() {
    return (
      <div>
        <h3>I am a class Component</h3>
      </div>
    )
  }
}

In above example, MyComponent refers to a class component which inherits render method from its parent component called React.Component

State and Lifecycle: Class components can have their own state and lifecycle methods (like componentDidMount, componentDidUpdate, and componentWillUnmount).

Example2:

class Greeting extends React.Component {
    render() {
        return <h1>Hello, {this.props.name}!</h1>;
    }
}

In the above example, this.props refers to the properties of parent component object and this.props.name refers to name property which is received by Greeting class component. 

React class component can have state which can be updated. Initial state is given in constructor of the class component. In the following example, local state is given in the constructor. The state can be updated using setState function in class component. Note that state is an object.

Example3:

import React from 'react'
class MyComponent extends React.Component {
constructor(props) {
   super(props)

 this.state = {
 firstname:"Bob",
 lastname:"Peterson"
   }
}
   render() {
      return (
  <div>
     <h3>I am a class Component</h3>
     <h4>{this.state.firstname}</h4>
     <h4>{this.state.lastname}</h4>
  </div>
      )
   }
}
export default MyComponent
Lifecycle Methods:
These are special methods in class components that get called at different stages of a component's life, such as mounting, updating, and unmounting. 
Examples are: componentDidMount, shouldComponentUpdate, componentDidUpdate, componentWillUnmount. 

Functional Components:
These are JavaScript functions that accept props as an argument and return React elements. 
Example:
function Greeting(props) {
  return <h1>Hello, {props.name}!</h1>;
}
Hooks: Functional components can use React hooks (like useState and useEffect) to manage state and side effects.

Now we look at props and state which are common in both class component and functional component.

Props:
Props (short for properties) are inputs to a component. They are passed to the component as attributes and can be accessed within a component.
Props are read-only and are used to pass data from parent components to child components.
Example: In the following functional component, props is passed as argument. The component receives the data of props from its parent component.

function Welcome(props) {
  return <h1>Hello, {props.name}</h1>;
}

In parent component, props data is passed as value of attribute as given below.

ReactDOM.render(<Welcome name="Sara" />, document.getElementById('root'));

State:
Definition: State is a built-in object that stores property values that belong to the component. When the state object changes, the component re-renders.
Usage: State is managed within the component and can change over time, usually in response to user actions. In class component state is managed using this.state and setState method. In functional component, it is managed using hooks. We will see them separately.
Example:

class Clock extends React.Component {
  constructor(props) {
    super(props);
    this.state = { date: new Date() };
  }

  componentDidMount() {
    this.timerID = setInterval(() => this.tick(), 1000);
  }

  componentWillUnmount() {
    clearInterval(this.timerID);
  }

  tick() {
    this.setState({
      date: new Date(),
    });
  }

  render() {
    return (
      <div>
        <h1>Hello, world!</h1>
        <h2>It is {this.state.date.toLocaleTimeString()}.</h2>
      </div>
    );
  }
}

Conclusion:
React components are versatile, reusable building blocks that allow developers to create complex and interactive UIs. They manage their own state, can receive data through props, and can be composed together to form more complex UIs. Understanding components is essential for developing applications in React.

A component must be capitalized in React. Why?

In React, component names must be capitalized because React treats components with lowercase names as native HTML elements. This convention helps React distinguish between custom components, which are defined by the user, and built-in HTML elements like `<div>`, `<span>`, `<input>`, etc. Note that HTML elements are in lowercase. Consider the following example:

// Incorrect: Component name is lowercase

const myComponent = () => {

  return <div>Hello, World!</div>;

};

// Correct: Component name is capitalized

const MyComponent = () => {

  return <div>Hello, World!</div>;

};

In the first example, `myComponent` is treated as a native HTML element by React because its name is lowercase. When React sees a lowercase name, it assumes it's a built-in HTML element. As a result, `myComponent` will be rendered as `<myComponent>` in the resulting HTML, which is not what you intend. In the second example, `MyComponent` is capitalized, adhering to the convention. React recognizes `MyComponent` as a custom component and renders it properly as a React component.

By capitalizing component names, you explicitly signal to React that you are referring to a custom component, ensuring proper rendering and avoiding any confusion or conflicts with HTML elements. This convention also enhances code readability and maintainability, making it clear which elements are built-in HTML elements and which are custom React components.

Global Variables in React component

Can we declare variables outside React component?

Yes, in React, you can declare variables outside of components. However, these variables will typically be in the scope of the file in which they are declared rather than being associated with any specific component. This is useful for storing data or values that are used across multiple components within the same file.

Here's an example:

// Outside component variable declaration
const globalVariable = 'I am global!';

function MyComponent() {
// Inside component usage of global variable
return 
{globalVariable}
; } export default MyComponent;

In this example, 'globalVariable' is declared outside of the 'MyComponent' function and can be accessed inside the component. However, it's important to note that using global variables like this can sometimes lead to unexpected behavior or make your code harder to reason about, especially as your application grows. So, it's generally a good practice to use props and state to manage data within React components whenever possible.

React JS - Create a new project using existing project

I have node_modules folder of an existing React app. How can I use it to create another React project?

The 'node_modules' folder from an existing React app can be used for creating another React app. This approach can be useful to avoid redownloading dependencies and to ensure consistency across multiple projects.

Here's how you can use the 'node_modules' folder from an existing React app in another React app development:

1. Copy the 'node_modules' folder:
Copy the entire 'node_modules' folder from the existing React app to the root directory of the new React app.

2. Ensure package.json:
Ensure that both React apps have a 'package.json' file with dependencies listed. If the new React app doesn't have a 'package.json' file, you can create one using 'npm init' or 'yarn init'. Edit the package file based on existing project's package.json file. You can copy old package.json file and change name and version values.

3. Install Missing Dependencies (if any):
After copying the 'node_modules' folder, check if there are any missing dependencies in the new React app by comparing the 'package.json' files. If there are missing dependencies, you can install them using 'npm install' or 'yarn install'.

4. Start the Development Server:
Once all dependencies are installed, you can start the development server of the new React app using 'npm start' or 'yarn start'.

By using the 'node_modules' folder from an existing React app in another React app development, you can save time on downloading dependencies and ensure that both projects use the same versions of libraries. However, be cautious with this approach, as it may lead to compatibility issues if the dependencies are tightly coupled with the original project's configuration or environment. It's also essential to ensure that you have the necessary licenses to use the dependencies in your new project.

Let us suppose that i have created a new package.json file and copied existing node_modules in the folder where package.json file is. Now if I run npm install then what will happen?

If you create a new 'package.json' file and copy the existing 'node_modules' folder into the same directory where the 'package.json' file is located, and then you run 'npm install', here's what will happen:

1. npm install will process the package.json file: When you run 'npm install', npm will read the 'package.json' file in the current directory to determine the dependencies that need to be installed.

2. npm will install any missing dependencies: If there are any dependencies listed in the 'package.json' file that are not present in the 'node_modules' folder, npm will download and install those dependencies.

3. npm will skip existing dependencies: If npm finds that a dependency listed in 'package.json' already exists in the 'node_modules' folder, it will skip the installation of that dependency. npm will not reinstall dependencies that are already present unless their versions are incompatible or missing.

4. npm will generate or update the package-lock.json file: If npm installs any new dependencies or updates existing ones, it will generate or update the 'package-lock.json' file to reflect the installed dependency tree and ensure consistency across installations.

In summary, running 'npm install' in this scenario will ensure that the dependencies listed in the 'package.json' file are installed in the 'node_modules' folder. If any dependencies are missing or outdated, npm will download and install them, but it will skip dependencies that are already present. This process helps to ensure that your project has all the required dependencies installed and that they are consistent with the 'package.json' file.

Note that npm will only install or update dependencies based on the information provided in the 'package.json' file.

React.StrictMode

What is React.StrictMode?
'React.StrictMode' is a tool provided by React that helps developers write more resilient code by highlighting potential problems and deprecated features in their application during development. When you wrap components with '<React.StrictMode>', React performs additional checks and warnings to help identify common issues such as:

1. Identifying unsafe lifecycle methods usage.
2. Warning about legacy string ref usage.
3. Detecting state updates inside 'render' methods.
4. Spotting unexpected side effects during rendering.
5. Highlighting potential problems with context usage.

By using 'React.StrictMode', you can catch and fix these issues earlier in the development process, which can lead to fewer bugs and better performance in your application.

It's important to note that 'React.StrictMode' only activates in development mode. In production builds, it has no effect and does not impact the behavior of your application.

To use 'React.StrictMode', you simply wrap your root component (usually located in 'src/index.js' or 'src/App.js') with '<React.StrictMode>'

Example

import React from "react";
import ReactDOM from "react-dom";
import App from "./App";

ReactDOM.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>,
  document.getElementById("root")
);

By doing this, all components inside '<App />' will be subject to the additional checks provided by 'React.StrictMode'. Once you've identified and fixed any issues highlighted by 'React.StrictMode', you can remove the wrapper in your production code if desired.

React manifest.json

What is manifest.json file in React project used for?
The 'manifest.json' file in a React project is a JSON file that provides metadata and configuration information about the web application. It's used to provide information to the browser and other web applications about how the application should behave when installed as a standalone app or added to the home screen of a mobile device. 

Here's what the 'manifest.json' file typically contains:

  1. Metadata: Information about the application, such as its name, short name, description, and author.
  2. Icons: URLs or paths to icons that represent the application in various contexts, such as on the home screen of a mobile device or in the browser's address bar.
  3. Colors: Theme colors used by the application, such as the background color or the color of the browser's toolbar.
  4. Display Settings: Configuration options related to how the application should be displayed, such as the display mode (e.g., fullscreen or standalone) and the orientation (e.g., portrait or landscape).
  5. Start URL: The URL that should be loaded when the application is launched.

Here's an example of what a 'manifest.json' file might look like:

{
"name": "My React App",
"short_name": "ReactApp",
"description": "A React web application",
"icons": [
{
"src": "icon-192x192.png",
"sizes": "192x192",
"type": "image/png"
}
],
"theme_color": "#ffffff",
"background_color": "#ffffff",
"display": "standalone",
"start_url": "/"
}

In a React project, the 'manifest.json' file is typically placed in the 'public' folder alongside the 'index.html' file. When the application is built and deployed, the 'manifest.json' file is served to the client as part of the static assets, allowing the browser and other web applications to access the metadata and configuration information it contains.

React JSX and CSS

React JSX and CSS
You can use CSS with JSX in React applications. There are several ways to apply CSS styles to JSX elements:

1. Inline Styles: You can apply styles directly to JSX elements using the 'style' attribute, which accepts an object with CSS properties and values.

import React from "react";

const MyComponent = () => {
  const textStyle = {
    color: "blue",
    fontSize: "16px",
    fontWeight: "bold",
  };

  return (
    <div>
      <p style={textStyle}>Hello, World!</p>
    </div>
  );
};

export default MyComponent;

2. External Stylesheets: You can import external CSS files into your React components and apply styles using class names.

import React from "react";
import "./styles.css"; // Import external CSS file

const MyComponent = () => {
  return (
    <div>
      <p className="my-text">Hello, World!</p>
    </div>
  );
};

export default MyComponent;

In 'styles.css':


   .my-text {
     color: blue;
     font-size: 16px;
     font-weight: bold;
   }


3. CSS Modules: React supports CSS Modules, which allows you to write modular CSS stylesheets that are scoped to the component they are imported into.


import React from "react";
import styles from "./MyComponent.module.css"; // Import CSS module

const MyComponent = () => {
  return (
    <div>
      <p className={styles.myText}>Hello, World!</p>
    </div>
  );
};

export default MyComponent;

And in 'MyComponent.module.css':


   .myText {
     color: blue;
     font-size: 16px;
     font-weight: bold;
   }

Using CSS with JSX allows you to style your React components in a flexible and modular way, whether it's applying styles inline, using external stylesheets, or utilizing CSS Modules for scoped styling.

React JSX

What is JSX?
JSX stands for JavaScript XML. It's a syntax extension for JavaScript that allows you to write HTML-like code within JavaScript. JSX makes it easier and more intuitive to define the structure and appearance of UI components in React applications.

With JSX, you can write code that looks similar to HTML, but it's actually JavaScript under the hood. JSX elements can represent HTML elements, React components, or fragments.

JSX is eventually transpiled into JavaScript code with the help of Babel like transpiler.

Here's an example of JSX code:

import React from "react";

// JSX element representing a React component
const MyComponent = () => {
  return (
    <div>
      <h1>Hello, World!</h1>
      <p>This is a JSX element.</p>
    </div>
  );
};

export default MyComponent;

In this example:

  • The HTML-like '<div>', '<h1>', and '<p>' elements are JSX elements which are given in return statement.
  • The 'MyComponent' function returns JSX, which represents the structure of the component's UI.
  • JSX elements can contain plain text, other JSX elements, JavaScript expressions, or React components.
  • JSX is compiled to JavaScript using a tool like Babel before being executed by the browser.

JSX allows you to write more declarative and expressive code when building UI components in React, making it easier to understand and maintain your codebase.
Example1:

import React from "react";

// JSX element representing a React component
const MyComponent = () => {
  return (
    <div>
      <h1>Hello, World!</h1>
      <p>This is a JSX element.</p>
    </div>
  );
};

export default MyComponent;

Example2:

import React from "react";

// JSX element representing a React component
const MyComponent = () => {
  return (
    <>
      <h1>Hello, World!</h1>
      <p>This is a JSX element.</p>
    </>
  );
};

export default MyComponent;

Example3:

import React from "react";

// JSX element representing a React component
const MyComponent = () => {
  return (
    <React.Fragment>
      <h1>Hello, World!</h1>
      <p>This is a JSX element.</p>
    </React.Fragment>
  );
};

export default MyComponent;

React Fragments
The above examples provided are valid JSX syntax, but they have a slight difference in how they define a React fragment.

Example1. Using '<div>' as a Wrapper: In this example, the JSX is wrapped inside a '<div>' element, which acts as a wrapper for the JSX elements. This is a common approach when you need to wrap multiple JSX elements in a single parent element.

Example2. Using a Fragment ('<>...</>'): In this example, a React fragment is used to wrap the JSX elements. Fragments allow you to group multiple JSX elements without introducing an additional DOM element. They are useful when you don't want to add extra nodes to the DOM but still need a parent-like container for your JSX elements.

Example3. Using a Fragment ('<React.Fragment>...</React.Fragment>'): This example is similar to Example2 but it is more explicit.

Conclusion:

All three approaches are valid and have their use cases. The choice between using a '<div>' wrapper or a fragment depends on your specific requirements and preferences. If you need a wrapper element for styling or structural reasons, you can use a '<div>'. If you want to avoid adding unnecessary elements to the DOM, you can use a fragment.

In above examples, we have used simple HTML-like text as JSX. In the following sections, we will see how to intersperse JavaScript code inside JSX.

JavaScript with JSX

In JSX, you can intersperse JavaScript code using curly braces '{}'. This allows you to embed JavaScript expressions, variables, or function calls directly within your JSX markup.

Here are some examples:

1. Embedding JavaScript Expressions:


import React from 'react';

const MyComponent = () => {
  const name = 'John';
  const greeting = 'Hello, ${name}!';

  return (
    <div>
      <p>{greeting}</p>
      <p>{2 + 2}</p>
    </div>
  );
};

export default MyComponent;

In this example, we use curly braces '{}' to embed JavaScript expressions ('greeting' and '2 + 2') directly within the JSX markup.

2. Using Variables:


import React from 'react';

const MyComponent = () => {
  const items = ['apple', 'banana', 'orange'];

  return (
    <ul>
      {items.map((item, index) => (
        <li key={index}>{item}</li>
      ))}
    </ul>
  );
};

export default MyComponent;
In this example, we use curly braces '{}' to embed a JavaScript expression inside the 'map()' function call, allowing us to dynamically generate a list of JSX elements based on an array of items.

3. Calling Functions:
import React from 'react';

const MyComponent = () => {
  const formatName = (firstName, lastName) => {
    return '${firstName} ${lastName}';
  };

  return (
    <div>
      <p>Hello, {formatName('John', 'Doe')}!</p>
    </div>
  );
};

export default MyComponent;
In this example, we use curly braces '{}' to call the 'formatName()' function and pass it arguments directly within the JSX markup.
Using curly braces '{}' allows you to seamlessly integrate JavaScript code within your JSX markup, making it easy to create dynamic and interactive UIs in React.

JSX Attributes
In React, JSX attributes are written in camel case. This means that attribute names in JSX follow the camel case convention, not the traditional kebab-case (dash-separated) convention commonly used in HTML.

For example, in HTML, you might write an attribute like 'class' and background-color as follows:
<div class="container" background-color="cyan">
  <!-content goes here -->
</div>

In JSX, however, you would write the same attributes as 'className' and backgroundColor:
<div className="container" backgroundColor="cyan">
  {/* content goes here */}
</div>

Similarly, other attributes follow the camelCase convention: 'tabindex' becomes 'tabIndex', 'for' becomes 'htmlFor', 'onclick' becomes 'onClick' etc.

This camelCase convention is a requirement in JSX to avoid conflicts with JavaScript reserved words (such as 'class'), and to maintain consistency with JavaScript naming conventions. When JSX is compiled, these camel case attributes are transformed into their kebab-case counterparts as expected by the DOM.

Loop in JSX
You can use JavaScript loops in JSX to dynamically render components or content based on an array or any iterable data structure. You typically use JavaScript map, forEach, or other loop methods within curly braces {} to iterate over data and generate JSX elements.

Here's an example of using a loop to render a list of items in JSX:
import React from 'react';

function MyComponent() {
  const items = ['apple', 'banana', 'cherry'];

  return (
    <div>
      <h1>Fruit List</h1>
      <ul>
        {items.map((item, index) => (
          <li key={index}>{item}</li>
        ))}
      </ul>
    </div>
  );
}

export default MyComponent;
In this example, the map function is used to iterate over the items array and generate <li> elements for each item. The key prop is important to provide React with a unique identifier for each list item.

React public folder

What is public folder in React project used for?
In a React project, the 'public' folder is used to store static assets and the HTML file that serves as the entry point for your application in the browser. Here's what each file in the 'public' folder is typically used for:

1. index.html: This is the main HTML file of your React application. It's a static file that serves as the entry point for your application in the browser. The 'index.html' file typically includes a '<div>' element with an 'id' of 'root', where your React application will be mounted by ReactDOM. It may also include other metadata and assets like stylesheets or scripts.

2. Other Static Assets: The 'public' folder can also contain other static assets such as images, fonts, or additional HTML files that you want to serve directly to the client without processing by Webpack or other build tools. These assets are typically referenced using relative URLs in your HTML or JSX files.

The contents of the 'public' folder are served as-is to the client without undergoing any transformation by Webpack or other build tools. This makes the 'public' folder useful for storing assets that don't need to be processed by the build pipeline, such as static HTML files or images.

Look at the public folder contents when create-react-app is used to setup React project.


React index.js and index.html

React Application Entry point

Which of these two files - Index.js or Index.html - is the starting point of react app?
In a typical React application, the starting point is usually the 'index.js' file. This file serves as the entry point for the application and is responsible for rendering the root component of the React application into the DOM.

The 'index.html' file, on the other hand, is the HTML template that serves as the container for the React application. It typically includes a '<div>' element with an 'id' attribute where the React application will be rendered. This '<div>' element acts as the mounting point for the React DOM renderer.

Here's a typical setup:

1. index.html: Contains the basic HTML structure and includes a '<div>' element with an 'id' where the React application will be mounted. For example:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>React App</title>
  </head>
  <body>
    <div id="root"></div>
  </body>
</html>

2. index.js: Contains the JavaScript code that initializes and renders the React application. For example:

import React from "react";
import ReactDOM from "react-dom";
import App from "./App";

ReactDOM.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>,
  document.getElementById("root")
);

In this setup, 'index.js' is the starting point of the React application. It imports the root component ('App') and renders it into the '<div id="root">' element specified in 'index.html'.

So, while both files play crucial roles in a React application, 'index.js' is typically considered the starting point where the React application is initialized and rendered into the DOM.

Are Index.js and Index.html files mandatory in ReactJS.?

In ReactJS, neither 'index.js' nor 'index.html' files are strictly mandatory, but they are conventional and widely used as starting points for React applications. Let's discuss each file:

1. index.js: This file is commonly used as the entry point for a React application. It typically contains code to render the root component of the React application into the DOM. While you can name this file differently or split its functionality across multiple files, having a single entry point makes it easier to understand and maintain the application structure. Look at the following code which is used to render element inside root element.

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

const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(
  <div>
    <h2>Welcome React</h2>
  </div>
);

You can use the following as well but it is deprecated:

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

const root = ReactDOM.render(<h2>Welcome React JS</h2>, document.getElementById("root"));

The render method can be passed a callback as third argument:

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

const root = ReactDOM.render(<h2>Welcome React JS</h2>, document.getElementById("root"), () =>
  console.log("The element is rendered or updated");

2. index.html: While not strictly required, an 'index.html' file is typically used as the HTML template for a React application. It provides the basic structure of the webpage and includes a placeholder element (often with the 'id' of 'root') where the React application will be mounted. The presence of an 'index.html' file is necessary for deploying a React application on the web. Look at the index.html file:

<!DOCTYPE html>
<html>
  <head>
    <title>React App Development</title>
  </head>
  <body>
    <div id="root"></div>
  </body>
</html>

While these files are conventional and commonly used, you have flexibility in naming and organizing your files based on your project's requirements. For instance, if you're using a different build tool or have specific deployment requirements, you might use a different file structure. However, adhering to conventions like using 'index.js' as the entry point and 'index.html' as the HTML template can make your project more understandable to other developers and align it with typical React application structures.

React Essential packages

Explain about the packages react , react-dom, react-scripts, and web-vitals in React

In a typical React project, several key packages are commonly used to build and run React applications. Here's an explanation of each of the packages you mentioned:

1. react:

  • The 'react' package is the core library of React. It provides the necessary APIs and components for building user interfaces in React.
  • This package includes components, hooks, and utilities for creating and managing React elements, handling component lifecycle, managing state, and handling events, among other functionalities.
  • When building a React application, the 'react' package is a fundamental dependency that must be included in your project.

2. react-dom:

  • The 'react-dom' package is a companion package to React that provides DOM-specific methods for working with React elements.
  • It includes APIs for rendering React components into the DOM, updating the DOM in response to changes in component state or props, and handling events from DOM elements.
  • 'react-dom' is used primarily in web applications to interact with the browser's DOM and render React components into the HTML document.

3. react-scripts:

  • The 'react-scripts' package is a set of scripts and configurations used for bootstrapping, building, and running React applications created with create-react-app (CRA).
  • It includes scripts for starting a development server, building production-ready bundles, running tests, and ejecting from the CRA setup to customize webpack configurations.
  • 'react-scripts' abstracts away the configuration complexity and provides a simple and streamlined development experience for React developers, especially for beginners or those who don't want to deal with webpack and other build tools directly.

4. web-vitals:

  • The 'web-vitals' package is a library for measuring and reporting real user experiences on the web.
  • It provides functions for measuring key performance metrics such as First Contentful Paint (FCP), Largest Contentful Paint (LCP), First Input Delay (FID), and Cumulative Layout Shift (CLS).
  • 'web-vitals' is often used in combination with other performance monitoring tools to track and improve the performance of web applications, particularly in terms of user-centric metrics.

These packages are essential dependencies in most React projects, with each serving a specific purpose in the development, rendering, and performance optimization of React applications.

Look at the following sample package.json file to install these essential dependencies.


{
  "name": "react-appk",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "react": "^18.3.1",
    "react-dom": "^18.3.1",
    "react-scripts": "5.0.1",
    "web-vitals": "^2.1.4"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  }
}

Hot Topics