install bootstrap in Reactjs

Bootstrap in a React application, you can install it via npm and then import it into your project.

1. Create a React Project (if you haven’t already)


npx create-react-app my-app
cd my-app

2. Install Bootstrap

Install Bootstrap via npm:


npm install bootstrap

3. Import Bootstrap CSS

You need to import the Bootstrap CSS file into your project. You can do this in the src/index.js file:


import 'bootstrap/dist/css/bootstrap.min.css';
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import './index.css';

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

4. Use Bootstrap Components

Now you can use Bootstrap classes in your React components. Here’s an example of using Bootstrap classes in a component:


import React from 'react';

export default function BootstrapExample() {
   return (
    <div className="container mt-5">
      <h1 className="text-center">Hello, Bootstrap!</h1>
      <button className="btn btn-primary">Click Me</button>
    </div>
  );
}

5. Optionally, Use React Bootstrap

If you prefer to use React components that wrap Bootstrap styles, you can install React Bootstrap:


npm install react-bootstrap

Then, import and use the React Bootstrap components:


import React from 'react';
import { Button, Container } from 'react-bootstrap';
import 'bootstrap/dist/css/bootstrap.min.css';

export default function ReactBootstrapExample() {
  return (
    <Container className="mt-5">
      <h1 className="text-center">Hello, React Bootstrap!</h1>
      <Button variant="primary">Click Me</Button>
    </Container>
  );
}

Bootstrap in Project Structure

Here is an example of what your project structure might look like after setting up Bootstrap:


my-app/
├── node_modules/
├── public/
├── src/
│   ├── App.js
│   ├── BootstrapExample.js
│   ├── ReactBootstrapExample.js
│   ├── index.css
│   └── index.js
├── .gitignore
├── package.json
├── README.md
└── yarn.lock

axios in Reactjs

Axios is a popular promise-based HTTP client for making HTTP requests, often used in React applications for interacting with APIs. It can be used to perform all types of HTTP requests and works in both the browser and Node.js environments.

How to Install

install Axios using npm or yarn:


npm install axios
# or
yarn add axios

Basic Usage

To use Axios in a React component, you typically import it and then make requests inside useEffect or event handlers.

Example:- get the products list through axios


import React, {useState} from 'react'
import axios from 'axios';
import { useEffect } from 'react';

export default function AxiosExample(){

    var [resData, SetresData] = useState([]);

    async function getProducts()
    {
    var data =  await axios.get('https://fakestoreapi.com/products')
    var results = data.data;
    SetresData(results); 
    }

    useEffect(()=>{
        getProducts()
    },[])

    return(
        <>
        <h1>Axios Example</h1>
        <div>
        {
           resData.map((item, index)=>{
            return <div key={index}>
                {item.title}
             </div>
           });
        
        }
        </div>
        </>
    )
}

Note:- in return we can use <> tag instead of div tag

apply css in reactjs

In React, there are several ways to apply CSS to your components, each with its own advantages. Here are the most common methods:

1. Inline Styles

Inline styles are defined directly within the component using the style attribute. The styles are written as an object, where the property names are camelCased versions of the CSS properties.


import React from 'react';
//MyComponent.jsx
export default function MyComponent() {
  const style = {
    color: 'green',
    backgroundColor: 'yellow',
    padding: '5px',
    borderRadius: '3px'
  };
  return <div style={style}>Hello World text with inline styles!</div>;
}

2. CSS Stylesheets

You can use traditional CSS stylesheets by importing them into your React component. This is the most straightforward way to style your components.

CSS File (styles.css)


.my-class {
    color: 'green',
    backgroundColor: 'yellow',
    padding: '5px',
    borderRadius: '3px'
}

React Component


import React from 'react';
import './styles.css';

//MyComponent.jsx
export default function MyComponent() {
  return <div className="my-class">This is styled with a CSS stylesheet!</div>;
}

3. CSS Modules

CSS Modules allow you to write CSS that is scoped locally to the component. This prevents conflicts with other styles and ensures that styles are only applied to the component they are intended for.

CSS Module (styles.module.css)


.my-class {
    color: 'green',
    backgroundColor: 'yellow',
    padding: '5px',
    borderRadius: '3px'
}

React Component


//CSSModulesComponent.jsx
import React from 'react';
import styles from './styles.module.css';

export default function CSSModulesComponent() {
  return <div className={styles.myClass}>This is styled with CSS Modules!</div>;
}

useCallback Hook

The useCallback hook in React is used to memoize callback functions. It returns a memoized version of the callback that only changes if one of the dependencies has changed. This is useful to optimize performance, particularly when passing callbacks to optimized child components that rely on reference equality to prevent unnecessary renders.

Basic Usage


import React, { useState, useCallback } from 'react';

export default function ExampleComponent() {
  const [count, setCount] = useState(0);

  const increment = useCallback(() => {
    setCount((prevCount) => prevCount + 1);
  }, []); // Empty array means the callback never changes

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={increment}>Click me</button>
    </div>
  );
}

When to Use useCallback

Prevent Re-creation of Functions: Use useCallback to prevent re-creation of functions on every render.

Optimized Child Components: Use useCallback when passing functions to memoized child components (React.memo) to prevent unnecessary re-renders.

Memoized Callback for Child Components


import React, { useState, useCallback } from 'react';

const ChildComponent = React.memo(({ onClick }) => {
  console.log('ChildComponent rendered');
  return <button onClick={onClick}>Click me</button>;
});

export default function ParentComponent() {
  const [count, setCount] = useState(0);

  const handleClick = useCallback(() => {
    setCount((prevCount) => prevCount + 1);
  }, []); // Empty array means the callback never changes

  return (
    <div>
      <p>Count: {count}</p>
      <ChildComponent onClick={handleClick} />
    </div>
  );
}

useMemo Hook

The useMemo hook in React is used to memoize the result of a function. This helps optimize performance by caching the result of an expensive computation and reusing it when the inputs (dependencies) haven’t changed.

useMemo is particularly useful when the computation is complex or when it prevents unnecessary re-rendering of child components.

Syntax:


useMemo(() => computeValue, [dependencies])

Basic Usage

useMemo takes two arguments: a function that returns the computed value and an array of dependencies.


import React, { useState, useMemo } from 'react';

export default function ExampleComponent({ items }) {
  const [filter, setFilter] = useState('');
 
  const filteredItems = useMemo(() => {
    return items.filter(item => item.includes(filter));
  }, [items, filter]);

  return (
    <div>
      <input
        type="text"
        value={filter}
        onChange={(e) => setFilter(e.target.value)}
        placeholder="Filter items"
      />
      <ul>
        {filteredItems.map((item, index) => (
          <li key={index}>{item}</li>
        ))}
      </ul>
    </div>
  );
}

When to Use useMemo

Expensive Computations: Use useMemo to memoize results of expensive computations that should only re-run when dependencies change.

Avoid Re-rendering: Use useMemo to prevent unnecessary re-renders of child components by memoizing data or calculations passed as props.

Avoid Re-rendering of Child Components


import React, { useState, useMemo } from 'react';

function ChildComponent({ data }) {
  console.log('ChildComponent rendered');
  return <div>{data}</div>;
}

const MemoizedChild = React.memo(ChildComponent);

export default function ParentComponent() {
  const [count, setCount] = useState(0);

  const data = useMemo(() => {
    return `Count is ${count}`;
  }, [count]);

  return (
    <div>
      <button onClick={() => setCount(count + 1)}>Increment</button>
      <MemoizedChild data={data} />
    </div>
  );
}



useEffect Hook

The useEffect hook in React allows you to perform side effects in function components. It is the combination of componentDidMount, componentDidUpdate, and componentWillUnmount lifecycle methods from class components. Side effects can include data fetching, subscriptions, or manually changing the DOM.

Basic Usage

The useEffect hook takes a function as its first argument and an optional dependency array as its second argument.


import React, { useState, useEffect } from 'react';

export default function ExampleComponent() {
  const [count, setCount] = useState(0);

  useEffect(() => {
    document.title = `You clicked ${count} times`;
  }, [count]); // Only re-run the effect if count changes

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>Click me</button>
    </div>
  );
}

Dependencies

The dependency array tells React when to re-run the effect. If it’s empty ([]), the effect runs only once after the initial render.


useEffect(() => {
  // Effect logic here
}, []); // This effect runs only once

Data Fetching

You can use useEffect to fetch data from an API when the component mounts.


import React, { useState, useEffect } from 'react';

export default function DataFetchingComponent() {
  const [data, setData] = useState(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    fetch('https://api.example.com/data')
      .then((response) => response.json())
      .then((data) => {
        setData(data);
        setLoading(false);
      });
  }, []); // Empty array means this effect runs once

  if (loading) {
    return <div>Loading...</div>;
  }

  return (
    <div>
      <h1>Data:</h1>
      <pre>{JSON.stringify(data, null, 2)}</pre>
    </div>
  );
}

Effect Dependencies

The dependency array is crucial for optimizing performance and avoiding unnecessary effect runs. If any value in the dependency array changes, the effect will run again.


import React, { useState, useEffect } from 'react';

export default function DependencyComponent({ userId }) {
  const [user, setUser] = useState(null);

  useEffect(() => {
    fetch(`https://api.example.com/users/${userId}`)
      .then((response) => response.json())
      .then((data) => setUser(data));
  }, [userId]); // Effect re-runs whenever userId changes

  if (!user) {
     return <div>Loading...</div>;
  }

  return (
    <div>
      <h1>{user.name}</h1>
      <p>{user.email}</p>
    </div>
  );
}

useState hook

The useState hook in React is a powerful feature that allows you to add state to functional components. It lets you manage state variables within your function components without needing to convert them into class components.

Basic Usage

The useState hook returns an array containing the current state and a function to update that state.


import React, { useState } from 'react';

export default function Counter() {
  // Declare a state variable named "count" and a function "setCount" to update it
  const [count, setCount] = useState(0);
  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>Click me</button>
    </div>
  );
}

Initial State

The argument passed to useState is the initial state value. It can be any type, including objects, arrays, or even other hooks.


import React, { useState } from 'react';

export default function UserProfile() {
  const [user, setUser] = useState({ name: 'John', age: 30 });

  const updateName = () => {
    setUser({ ...user, name: 'Jane' });
  };

  return (
    <div>
      <p>Name: {user.name}</p>
      <p>Age: {user.age}</p>
      <button onClick={updateName}>Change Name</button>
    </div>
  );
}

Updating State

The state updating function (setState) can take the new state value directly or a function that receives the current state and returns the new state.


import React, { useState } from 'react';

export default function Counter() {
  const [count, setCount] = useState(0);

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>Click me</button>
    </div>
  );
}

Functional State Update

Using a function to update state is useful when the new state depends on the previous state.


import React, { useState } from 'react';

export default function Counter() {
  const [count, setCount] = useState(0);

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(prevCount => prevCount + 1)}>Click me</button>
    </div>
  );
}

Using Multiple State Variables

You can use multiple useState hooks to manage different state variables.


import React, { useState } from 'react';

export default function MultiStateComponent() {
  const [name, setName] = useState('John');
  const [age, setAge] = useState(30);

  return (
    <div>
      <p>Name: {name}</p>
      <p>Age: {age}</p>
      <button onClick={() => setName('Jane')}>Change Name</button>
      <button onClick={() => setAge(35)}>Change Age</button>
    </div>
  );
}

React Form

React Form allow for handling user input and managing form submission. React provides controlled and uncontrolled components for handling forms.

1. Controlled Components

In controlled components, form data is handled by the component’s state.

Functional Components with Hooks


import React, { useState } from 'react';

export default function MyForm() {
  const [name, setName] = useState('');
  const [age, setAge] = useState('');

  const handleNameChange = (event) => {
    setName(event.target.value);
  };

  const handleAgeChange = (event) => {
    setAge(event.target.value);
  };

  const handleSubmit = (event) => {
    event.preventDefault();
    alert(`Name: ${name}, Age: ${age}`);
  };

  return (
    <form onSubmit={handleSubmit}>
      <label>
        Name:
        <input type="text" value={name} onChange={handleNameChange} />
      </label>
      <br />
      <label>
        Age:
        <input type="number" value={age} onChange={handleAgeChange} />
      </label>
      <br />
      <button type="submit">Submit</button>
    </form>
  );
}

2. Uncontrolled Components

In uncontrolled components, form data is handled by the DOM itself.

Using ref in Functional Components


import React, { useRef } from 'react';

export default function MyForm() {
  const nameRef = useRef(null);
  const ageRef = useRef(null);

  const handleSubmit = (event) => {
    event.preventDefault();
    alert(`Name: ${nameRef.current.value}, Age: ${ageRef.current.value}`);
  };

  return (
    <form onSubmit={handleSubmit}>
      <label>
        Name:
        <input type="text" ref={nameRef} />
      </label>
      <br />
      <label>
        Age:
        <input type="number" ref={ageRef} />
      </label>
      <br />
      <button type="submit">Submit</button>
    </form>
  );
}

Handling Form Validation

Form validation can be added by checking the form data before submission.

Functional Components with Hooks


import React, { useState } from 'react';

export default function MyForm() {
  const [formState, setFormState] = useState({ name: '', age: '' });
  const [errors, setErrors] = useState({ name: '', age: '' });

  const handleChange = (event) => {
    const { name, value } = event.target;
    setFormState((prevState) => ({
      ...prevState,
      [name]: value,
    }));
  };

  const validateForm = () => {
    let valid = true;
    let errors = {};

    if (!formState.name) {
      valid = false;
      errors.name = 'Name is required';
    }

    if (!formState.age) {
      valid = false;
      errors.age = 'Age is required';
    } else if (isNaN(formState.age)) {
      valid = false;
      errors.age = 'Age must be a number';
    }

    setErrors(errors);
    return valid;
  };

  const handleSubmit = (event) => {
    event.preventDefault();
    if (validateForm()) {
      alert(`Name: ${formState.name}, Age: ${formState.age}`);
    }
  };

  return (
    <form onSubmit={handleSubmit}>
      <label>
        Name:
        <input type="text" name="name" value={formState.name} onChange={handleChange} />
        {errors.name && <span>{errors.name}</span>}
      </label>
      <br />
      <label>
        Age:
        <input type="number" name="age" value={formState.age} onChange={handleChange} />
        {errors.age && <span>{errors.age}</span>}
      </label>
      <br />
      <button type="submit">Submit</button>
    </form>
  );
}
create form through use react-hook-form library

install react-hook-form


npm install react-hook-form

create form through react-hook-form with validation


import React from 'react';
import { useForm } from 'react-hook-form';

export default function SignUp(){

    const {register,handleSubmit,formState: { errors }} = useForm();

    const signupSubmit = async (data) =>{
      console.log(data);
    }

    return(
        <div>
        <h1>Signup Form</h1>
        <form onSubmit={handleSubmit(signupSubmit)}>

        <div className='container'>

            <div className="row">
             FirstName:
             <input type="text" id="firstName" {...register('firstName',{required:{value:true,message:"First Name is required"},maxLength:{value:10, message:"First Name should be less than or equal to 10"}})} />
             {errors.firstName && <p className='alert alert-danger'>{errors.firstName?.message}</p> }
            </div>
            <div className="row my-2">
             LastName:
             <input type="text" id="lastName" {...register('lastName',{required:{value:true,message:"Last Name is required"},maxLength:{value:10, message:"Last Name should be less than or equal to 10"}})} />
             {errors.lastName && <p className='alert alert-danger'>{errors.lastName?.message}</p> }
            </div>
            <div><button className='btn btn-primary'>Submit</button></div>

        </div>
        </form>
        </div>
    )
}

Conditional rendering

Conditional rendering in React allows you to render different components or elements based on certain conditions. Here are some common ways to achieve conditional rendering in React:

Using if statements


//MyComponent.jsx
function MyComponent(props) {
  if (props.isLoggedIn) {
    return <h1>Welcome back!</h1>;
  } else {
    return <h1>Please sign up.</h1>;
  }
}

Using the ternary operator


//MyComponent.jsx
function MyComponent(props) {
  return (
    <div>
      {props.isLoggedIn ? <h1>Welcome back!</h1> : <h1>Please sign up.</h1>}
   </div>
  );
}

Using logical && operator


//MyComponent.jsx
function MyComponent(props) {
  return (
    <div>
      {props.isLoggedIn && <h1>Welcome back!</h1>}
      {!props.isLoggedIn && <h1>Please sign up.</h1>}
    </div>
  );
}

Conditional rendering with switch statement


//MyComponent.jsx
function MyComponent(props) {
  switch (props.status) {
    case 'loading':
      return <div>Loading...</div>;
    case 'error':
      return <div>Error!</div>;
    case 'success':
      return <div>Data loaded successfully!</div>;
    default:
      return null;
  }
}

Using Component with conditional rendering

You can create separate components for different conditions and use them conditionally.


//welcome.jsx
function Welcome() {
  return <h1>Welcome back!</h1>;
}

//SignUp.jsx
function SignUp() {
  return <h1>Please sign up.</h1>;
}

//MyComponent.jsx
function MyComponent(props) {
  return (
    <div>
      {props.isLoggedIn ? <Welcome /> : <SignUp />}
    </div>
  );
}

React Router

React Router is a popular library for handling routing in React applications. It allows you to define routes in your application and navigate between different components or views without reloading the page.

Here’s a step-by-step example of how to set up and use React Router in a simple React application:

Install React Router:

First, you need to install React Router.


npm install react-router-dom

Create Components:

Next, create the components for Home, About, and Contact.


//home.jsx
import React from 'react';

function Home() {
  return <h2>Home</h2>;
}

Now, create the About.jsx component


// src/components/About.jsx
import React from 'react';

function About() {
  return <h2>About</h2>;
}

export default About;

Now, create the Contact.jsx component


// src/components/Contact.jsx
import React from 'react';

function Contact() {
  return <h2>Contact</h2>;
}

export default Contact;

Set up the Router:

In your src directory, create a new file headerMenu.jsx (if it doesn’t already exist) and set up the router.


import React from "react";
import {Link} from 'react-router-dom';
export default function HeaderMenu(){

    return (
    <>
    <nav className="navbar navbar-expand-lg bg-primary">
  <div className="container-fluid">
 
    <div className="collapse navbar-collapse" id="navbarSupportedContent">
      <ul className="navbar-nav me-auto mb-2 mb-lg-0">
        <li className="nav-item ">
          <Link className="nav-link active  text-light" aria-current="page" to="/">Home</Link>
        </li>
        <li className="nav-item">
          <Link className="nav-link text-light" to="/about-us">AboutUs</Link>
        </li>
        <li className="nav-item">
          <Link className="nav-link text-light" to="/contact-us">ContactUs</Link>
        </li>
      </ul>
      
    </div>
  </div>
</nav>
</>
    )

}

In the above example, we use Link instead of anchor (a) tag and we use to instead of href.

create Router.Example.jsx


import React from "react";
import HeaderMenu from "./HeaderMenu";
import {BrowserRouter,Routes,Route} from 'react-router-dom'
import Aboutus from "./About";
import ContactUs from "./Contact";
import Home from "./Home";

export default function RoutingExample(){

    return (
        <>
        <BrowserRouter>
        <HeaderMenu/>
        <Routes>
           <Route path="/" element={<Home/>}></Route>
            <Route path="/about-us" element={<Aboutus/>}></Route>
            <Route path="/contact-us" element={<ContactUs/>}></Route>
        </Routes>
        </BrowserRouter>
        
        </>
    )

}

This simple example demonstrates the basic usage of React Router. Here’s a brief explanation of the key parts:

BrowserRouter (aliased as Router): Wraps your application and enables routing.

Link: Used to create navigation links.

Switch: Renders the first child <Route> that matches the location.

Route: Defines a route and the component to render when the route matches.

What is List and keys

lists and keys are essential concepts for efficiently rendering and managing collections of elements. They help React identify which items have changed, been added, or been removed, making it possible to optimize rendering.

Lists

Lists in React are used to render multiple items dynamically. Typically, you’ll map over an array of data to create a list of elements.

Step1:- create NumberList.jsx file


import React from 'react';

function NumberList(props) {
  const numbers = props.numbers;
  const listItems = numbers.map((number) =>
    
  • {number}
  • ); return ( <ul>{listItems}</ul> ); }

    Step2:- create App.jsx file and include NumberList component

    
    import React from 'react';
    const numbers = [1, 2, 3, 4, 5];
    function App() {
      return <NumberList numbers={numbers} />;
    }
    export default App;
    

    In this example:

    1. numbers.map((number) => <li key={number.toString()}>{number}</li>) is used to transform the array of numbers into an array of list items (<li> elements).
    2. Each item in the array is rendered as an <li> element.
    Keys

    Keys help React identify which items have changed, been added, or been removed. They are crucial for dynamic lists where items can be reordered, inserted, or deleted.

    Why Keys are Important

    Keys should be given to the elements inside the array to give them a stable identity:

    Performance Optimization: Helps React update the UI more efficiently by minimizing the number of DOM manipulations.

    Consistency: Ensures that elements are re-used and not unnecessarily recreated, which is particularly important when dealing with complex components.

    Best Practices for Keys

    Use Unique Identifiers: If your data has a unique identifier, use it as the key.

    Avoid Using Index as Key: Using array indexes as keys can lead to issues with component state and reordering. It’s usually better to use stable, unique identifiers.

    Step1:- create TodoList.jsx file

    
    //TodoList.jsx
    import React from 'react';
    
    const todos = [
      { id: 1, text: 'Learn React' },
      { id: 2, text: 'Build a React App' },
      { id: 3, text: 'Deploy the App' }
    ];
    
    function TodoList() {
      const listItems = todos.map((todo) =>
        <li key={todo.id}>{todo.text}</li>
      );
      return (
        <ul>{listItems}</ul>
      );
    }
    

    Step2:- create App.jsx file and include TodoList component

    
    //App.jsx
    function App() {
      return <TodoList />;
    }
    
    export default App;
    

    In this example, each todo item has a unique id which is used as the key.

    React Hooks

    In React, a hook is a special function that allows you to use state and other React features in functional components. Prior to hooks, state and lifecycle methods were only available in class components. Hooks were introduced in React 16.8 to allow functional components to manage state and side effects, making them more powerful and flexible.

    Basic Concepts of Hooks

    State Hook (useState): Allows you to add state to functional components.

    Effect Hook (useEffect): Lets you perform side effects in function components.

    Context Hook (useContext): Lets you use context to pass data through the component tree without having to pass props down manually at every level.

    Rules of Hooks
    1. Only call hooks at the top level: Don’t call hooks inside loops, conditions, or nested functions. This ensures hooks are called in the same order each time a component renders.
    2. Only call hooks from React functions: Call them from within React functional components or custom hooks, not regular JavaScript functions.
    Benefits of Hooks
    1. Simpler Code: Functional components with hooks are generally simpler and easier to read than class components.
    2. Reusability: Hooks allow you to reuse stateful logic across multiple components.
    3. Better Organization: Hooks let you split one component into smaller functions based on what pieces are related (e.g., setting up a subscription or fetching data).
    Basic Hooks

    useState

    The useState hook lets you add state to a functional component. It returns an array with two elements: the current state value and a function to update it.

    
    import React, { useState } from 'react';
    
    function Counter() {
      const [count, setCount] = useState(0);
    
      return (
        <div>
          <p>You clicked {count} times</p>
          <button onClick={() => setCount(count + 1)}>Click me</button>
        </div>
      );
    }
    
    export default Counter;
    
    

    useEffect

    The useEffect hook lets you perform side effects in function components. It’s similar to lifecycle methods in class components (componentDidMount, componentDidUpdate, componentWillUnmount).

    
    import React, { useState, useEffect } from 'react';
    
    function Example() {
      const [count, setCount] = useState(0);
    
      useEffect(() => {
        // Update the count
         console.log(`You clicked ${count} times`);
      }, [count]); // Only re-run the effect if count changes
    
      return (
        <div>
          <p>You clicked {count} times</p>
          <button onClick={() => setCount(count + 1)}>Click me</button>
        </div>
      );
    }
    
    export default Example;
    

    useContext

    The useContext hook in React allows you to consume context in a functional component without needing to wrap your component in a Consumer component. This makes the code more concise and easier to read. Context provides a way to pass data through the component tree without having to pass props down manually at every level.

    Creating and Using Context

    1. Create a Context: Use the createContext function to create a context.
    2. Provide a Context Value: Use a Provider component to pass the context value to the tree.
    3. Consume Context: Use the useContext hook to consume the context value in a functional component.

    Step-by-Step Example

    Step 1: Create a Context

    First, create a context using the createContext function.

    
    import { createContext } from 'react';
    
    // Create a context with 'light' as the default value
    const ThemeContext = createContext('light');
    
    export { ThemeContext };
    

    Step 2: Provide a Context Value

    Wrap your component tree with a Provider component and pass the context value.

    
    //index.js
    import React from 'react';
    import ReactDOM from 'react-dom';
    import App from './App';
    import { ThemeContext } from './ThemeContext';
    
    ReactDOM.render(
      <ThemeContext.Provider value="dark">
        <App />
      </ThemeContext.Provider>,
      document.getElementById('root')
    );
    
    

    Step 3: Consume Context

    Use the useContext hook to consume the context value in a functional component.

    
    //ThemedButton.jsx
    import React, { useContext } from 'react';
    import { ThemeContext } from './ThemeContext';
    
    function ThemedButton() {
      const theme = useContext(ThemeContext);
      return <button style={{ background: theme === 'dark' ? '#333' : '#fff' }}>Themed Button</button>;
    }
    
    export default ThemedButton;
    
    

    App.jsx

    
    import React from 'react';
    import ThemedButton from './ThemedButton';
    
    function App() {
      return (
        <div>
          <ThemedButton />
        </div>
      );
    }
    
    export default App;
    
    

    Lifting state up

    Lifting state up is a common pattern in React for sharing state between multiple components. When several components need to reflect the same changing data, it is recommended to lift the shared state up to their closest common ancestor. This allows you to manage state in one place and pass it down as props to the components that need it.

    Here’s a step-by-step guide on how to lift state up in React:

    Identify the common ancestor: Determine the closest common ancestor component that needs to manage the shared state.

    Move the state to the common ancestor: Declare the state in the common ancestor component.

    Pass the state down as props: Pass the state from the common ancestor to the child components that need it.

    Pass the state updater function down as props: If child components need to update the state, pass the state updating function down to them as props.

    Example: Simple Input and Display

    Let’s create a simple React application where an input component updates a message, and the message is displayed in another component.

    Step 1: Create the Common Ancestor Component

    Let’s start by creating the common ancestor component, App, which will hold the state.

    
    import React, { useState } from 'react';
    import MessageInput from './MessageInput';
    import DisplayMessage from './DisplayMessage';
    
    function App() {
      const [message, setMessage] = useState('');
    
      return (
        <div>
          <MessageInput message={message} onMessageChange={setMessage} />
          <DisplayMessage message={message} />
        </div>
      );
    }
    
    export default App;
    
    

    Step 2: Create the Input Component

    The MessageInput component will receive the message and the state updater function as props.

    
    import React from 'react';
    
    function MessageInput({ message, onMessageChange }) {
      const handleChange = (e) => {
        onMessageChange(e.target.value);
      };
    
      return (
        <div>
          <input type="text" value={message} onChange={handleChange} placeholder="Type a message" />
        </div>
      );
    }
    
    export default MessageInput;
    
    

    Step 3: Create the Display Component

    The DisplayMessage component will receive the message as a prop and display it.

    
    import React from 'react';
    
    function DisplayMessage({ message }) {
      return (
        <div>
          <p>{message}</p>
        </div>
      );
    }
    
    export default DisplayMessage;
    

    Work Process:

    1. The App component holds the state for the message.
    2. The MessageInput component receives the current message and a function to update it as props. When the input value changes, it calls the onMessageChange function, which updates the state in the App component.
    3. The DisplayMessage component receives the current message as a prop and displays it.

    By lifting the state up to the App component, both MessageInput and DisplayMessage can share the same state and remain synchronized.

    What is state

    In React, state refers to a built-in object that holds data or information about the component. It is used to create dynamic and interactive components by enabling React to keep track of the changes in the component’s data over time. When the state of a component changes, React re-renders the component to reflect the new state, ensuring the UI is always up to date.

    Key Characteristics of State:

    Mutable: state is mutable and can be changed by the component itself while props, which are read-only.

    Private: State is local to the component where it is defined and cannot be accessed or modified directly by other components.

    Triggers Re-render: When state changes, React automatically re-renders the component to reflect the updated state.

    Managing State in Functional Components:

    With the introduction of React Hooks in version 16.8, functional components can now use state through the useState hook.

    
    import React, { useState } from 'react';
    
    function Counter() {
      // Declare a state variable named "count" with an initial value of 0
      const [count, setCount] = useState(0);
    
      // Function to increment the count
      const increment = () => {
        setCount(count + 1);
      };
    
      return (
        <div>
          <p>You clicked {count} times</p>
          <button onClick={increment}>Click me</button>
        </div>
      );
    }
    export default Counter;
    
    Explanation:

    useState Hook:

    The useState hook is used to declare a state variable. It takes an initial state value as an argument and returns an array with two elements:

    1. The current state value (count).
    2. A function to update the state (setCount).

    State Initialization:

    const [count, setCount] = useState(0); initializes the state variable count with an initial value of 0.

    Updating State:

    The increment function updates the state by calling setCount(count + 1). This triggers a re-render of the component with the new state value.

    Rendering the Component:

    The component renders a div containing a paragraph that displays the current count and a button that increments the count when clicked.

    Managing State in Class Components:

    Before hooks, class components were the primary way to manage state in React. State is managed through the this.state object and updated using the this.setState method.

    
    import React, { Component } from 'react';
    
    class Counter extends Component {
      constructor() {
        super();
        // Initialize state
        this.state = { count: 0 };
    
      }
    
      // Method to update state
      increment() {
        this.setState({count:this.state.count+1})
      }
    
      render() {
        return (
          <div>
            <p>You clicked {this.state.count} times</p>
            <button onClick={this.increment}>Click me</button>
          </div>
        );
      }
    }
    
    export default Counter;
    
    
    Explanation:

    State Initialization:

    State is initialized in the constructor using this.state = { count: 0 };.

    Updating State:

    The increment method updates the state using this.setState, which triggers a re-render.

    Rendering the Component:

    The render method returns JSX that renders the current state and a button to update the state.

    What is jsx

    JSX (JavaScript XML) is a syntax extension for JavaScript, commonly used with React to describe what the UI should look like. It allows you to write HTML structures within JavaScript code, making the code more readable and expressive. Here’s an overview of JSX in the context of React:

    Key Features of JSX:

    HTML-like Syntax: JSX allows you to write HTML-like code directly within JavaScript files. For example:

    
    const element = 

    Hello, world!

    ;

    This code creates a React element that represents an <h1> element with the text “Hello, world!”.

    Embedded Expressions: You can embed JavaScript expressions within JSX using curly braces {}. For example:

    
    const name = 'John';
    const element = 

    Hello, {name}!

    ;

    This will render as <h1>Hello, John!</h1>.

    Components: JSX is often used to define React components. Components can be functions or classes that return JSX:

    
    function Welcome(props) {
      return 

    Hello, {props.name}

    ; }

    This function component takes a name prop and renders it within an <h1> element.

    Attributes: You can use attributes in JSX similarly to HTML. However, in JSX, attribute names follow camelCase convention instead of kebab-case. For example:

    
    const element = <img src="logo.png" className="logo" alt="Logo" />;
    

    In this example, we use className attribute instead of class in jsx file in Reactjs.

    Example2:

    
    <h1 style={{color:"white", backgroundColor:"red"}}>Hello Css Example</h1>
    

    In this example, we use style attribute has backgroundColor property in a camelCase in jsx in Reactjs.

    How JSX Works:

    JSX is not valid JavaScript by itself. Browsers cannot read it directly. Therefore, it needs to be transpiled to regular JavaScript using tools like Babel. During the build process, Babel transforms JSX into React.createElement() calls:

    
    const element = <h1>Hello, world!</h1>;
    // Transpiles to:
    const element = React.createElement('h1', null, 'Hello, world!');
    
    Advantages of JSX:

    Readability: JSX makes the structure of the component more understandable and similar to HTML, making it easier to visualize the UI structure.

    Integration: Embedding JavaScript expressions directly within the markup allows for dynamic content rendering and complex UI interactions.

    Componentization: JSX promotes the creation of reusable UI components.

    Class Component

    Class components in React.js are ES6 classes that extend from React.Component and must contain a render method that returns JSX. Here’s a step-by-step guide to creating and using class components in React:

    Creating a Class Component

    A class component is a JavaScript class that extends React.Component and includes a render method.

    Create the Component File: Create a new file for your component, e.g., MyComponent.js.

    
    // src/MyComponent.jsx
    import React, { Component } from 'react';
    class MyComponent extends Component {
      render() {
        return (
          <div>
            <h1>Hello, world!</h1>
          </div>
        );
      }
    }
    export default MyComponent;
    

    Using the Component: Import and use this component in your main application file, e.g., App.js.

    
    // src/App.jsx
    import React, { Component } from 'react';
    import MyComponent from './MyComponent';
    
    class App extends Component {
      render() {
        return (
          <div>
            <MyComponent />
          </div>
        );
      }
    }
    export default App;
    

    Output will be:- Hello, World!

    Adding Props to a Class Component

    Props are used to pass data from parent to child components.

    Modify the Component to Accept Props:

    
    // src/MyComponent.jsx
    import React, { Component } from 'react';
    
    class MyComponent extends Component {
      render() {
        return (
          <div>
            <h1>Hello, {this.props.name}!</h1>
          </div>
        );
      }
    }
    export default MyComponent;
    
    

    Pass Props to the Component:

    
    // src/App.jsx
    import React, { Component } from 'react';
    import MyComponent from './MyComponent';
    
    class App extends Component {
      render() {
        return (
          <div>
            <MyComponent name="World" />
          </div>
        );
      }
    }
    export default App;
    
    

    Output will be:- Hello, World!

    Function Component

    Function components in React.js are a way to create components using JavaScript functions. These components are simpler than class components and are often easier to read and test. Here’s a step-by-step guide to creating and using function components in React:

    Creating a Function Component

    A function component is a JavaScript function that returns a React element.

    Create the Component File: Create a new file for your component, e.g., MyComponent.js.

    
    // src/MyComponent.jsx
    import React from 'react';
    
    const MyComponent = () => {
      return (
        <div>
          <h1>Hello, world!</h1>
        </div>
      );
    };
    
    export default MyComponent;
    
    

    Using the Component: Import and use this component in your main application file, e.g., App.js.

    
    // src/App.jsx
    import React from 'react';
    import MyComponent from './MyComponent';
    
    const App = () => {
      return (
        <div>
          <MyComponent />
        </div>
      );
    };
    
    export default App;
    

    Output will be: Hello, World!

    Adding Props to a Function Component

    Props are used to pass data from parent to child components.

    Modify the Component to Accept Props:

    
    // src/MyComponent.jsx
    import React from 'react';
    
    const MyComponent = (props) => {
      return (
        <div>
          <h1>Hello, {props.name}!</h1>
        </div>
      );
    };
    
    export default MyComponent;
    
    

    Pass Props to the Component:

    
    // src/App.jsx
    import React from 'react';
    import MyComponent from './MyComponent';
    
    const App = () => {
      return (
        <div>
          <MyComponent name="World" />
        </div>
      );
    };
    
    export default App;
    

    Output will be: Hello, World!

    React Component

    React components are the fundamental building blocks of a React application. They encapsulate parts of the user interface, making it easy to create complex UIs from smaller, isolated pieces of code. Components can be either functional or class-based, and they can manage their own state and lifecycle methods. Here’s an in-depth look at React components:

    Types of Components
    1. Functional Components
    2. Class Components

    Functional Components

    Functional components are simpler and are typically used for components that don’t need to manage state or lifecycle methods. They are just JavaScript functions that accept props as an argument and return React elements.

    Example of a functional component:

    
    //src/MyComponent.js
    import React from 'react';
    
    function Welcome() {
      return 

    Hello World!

    ; } export default Welcome;

    In this example, Welcome is a functional component and returns a React element.

    Class Components

    Class components are more feature-rich. They allow you to use additional features like local state and lifecycle methods. Class components extend React.Component.

    Example of a class component:

    
    src/Greetings.js
    import React, { Component } from 'react';
    
    class Greetings extends React.Component {
      render() {
        return 

    Hello World!

    ; } } export default Greetings;

    In this example, Greetings is a class component that renders the same output as the functional component.

    Rendering a component

    Rendering a component in React.js involves creating a component and then rendering it in the DOM.

    Import and use the component in your main application file (src/App.js).

    Rendering a function component
    
    // src/App.js
    import React from 'react';
    import MyComponent from './MyComponent';
    
    const App = () => {
      return (
        <div>
           <MyComponent />
         </div>
      );
    };
    
    export default App;
    

    In this example, output will be Hello World!

    Rendering a class component

    It will be same as a function component

    
    // src/App.js
    import React from 'react';
    import Greetings from './Greetings';
    
    const App = () => {
      return (
        <div>
          <Greetings />
        </div>
      );
    };
    
    export default App;
    

    In this example, output will be Hello World!

    How to install Reactjs

    To install React.js, you need to set up your development environment. Here’s a step-by-step guide to getting started:

    Prerequisites

    Node.js and npm: React.js requires Node.js and npm (Node Package Manager) to be installed on your machine. You can download and install Node.js from nodejs.org.

    Step-by-Step Installation
    Install Node.js and npm

    Download the installer for your operating system from nodejs.org and follow the installation instructions. This will install both Node.js and npm.

    Create a New React Application

    The easiest way to create a new React application is by using the Create React App CLI tool. This tool sets up a new React project with a sensible default configuration.

    1. Open your terminal or command prompt.
    2. Run the following command to install Create React App globally:
    
    npm install -g create-react-app
    

    After the installation is complete, create a new React application by running:

    
    npx create-react-app my-app
    

    Replace my-app with the name of your project.

    Navigate to your project directory:

    
    cd my-app
    

    Start the development server:

    
    npm start
    

    Your new React app should now be running on http://localhost:3000. The development server will automatically reload the page if you make edits to your code.

    Project Structure

    After creating your React application, the project directory will look something like this:

    
    my-app
    ├── README.md
    ├── node_modules
    ├── package.json
    ├── public
    │   ├── favicon.ico
    │   ├── index.html
    │   └── ...
    ├── src
    │   ├── App.css
    │   ├── App.js
    │   ├── App.test.js
    │   ├── index.css
    │   ├── index.js
    │   └── ...
    
    

    public: This folder contains the public assets of your application. The main file here is index.html, which serves as the entry point for your app.

    src: This folder contains the source code of your application. The main files to note here are index.js and App.js.

    What is Reactjs

    React (also known as React.js or ReactJS) is a JavaScript library developed by Facebook for building user interfaces, specifically single-page applications where a fast, interactive user experience is crucial. It allows developers to create large web applications that can update and render efficiently in response to data changes.

    Key Features of React

    1) Component-Based Architecture:
    Components: The building blocks of a React application. A component can be a function or a class, and it typically returns a React element (JSX) that describes how a section of the UI should appear

    Reusable: Components can be reused across the application, making code more modular and maintainable.

    2) JSX (JavaScript XML):

    Syntax Extension: JSX is a syntax extension for JavaScript that looks similar to XML or HTML. It allows developers to write UI components using a syntax that closely resembles HTML, making it easier to understand and maintain the structure of the UI.

    Transformation: JSX is transformed into JavaScript at runtime.

    3) Virtual DOM:

    Efficiency: React uses a virtual DOM to improve performance. Instead of manipulating the browser’s DOM directly, React creates a virtual DOM and updates it in response to changes. It then compares the virtual DOM with the real DOM (using a process called “reconciliation”) and updates only the parts of the DOM that have changed.

    Performance: This approach minimizes the number of direct DOM manipulations, which are typically slow, thereby enhancing the performance of the application.

    4) One-Way Data Binding:

    Unidirectional Data Flow: React enforces a one-way data flow where data flows from parent components to child components via props. This makes it easier to understand and debug the state of an application.

    5) State Management:

    State: React components can maintain local state, which allows them to manage data that changes over time. When the state of a component changes, React automatically re-renders the component and its children to reflect the new state.

    State Management Libraries: For larger applications, state management libraries like Redux, MobX, or the Context API can be used to manage complex state interactions.

    6) Lifecycle Methods:

    Class Components: React provides lifecycle methods for class components, which allow developers to execute code at specific points in a component’s life (e.g., mounting, updating, unmounting).

    Hooks: In functional components, React hooks (like useEffect) provide similar functionality, allowing developers to perform side effects in function components.

    7) React Hooks:

    State and Lifecycle: Hooks like useState and useEffect allow functional components to use state and other React features without writing class components.

    Custom Hooks: Developers can create custom hooks to encapsulate reusable logic.

    Advantages of Using React

    Declarative: React makes it easier to design interactive UIs. Developers can design views for each state in their application, and React will update and render the right components when the data changes.

    Component-Based: The ability to build encapsulated components that manage their own state, then compose them to make complex UIs.

    Efficient Updates: The virtual DOM ensures minimal updates to the actual DOM, leading to improved performance.

    Ecosystem: A vast ecosystem of libraries and tools, including React Router for navigation, Redux for state management, and many more.

    Use Cases

    React is commonly used for:

    Single-Page Applications (SPAs): Where the goal is to create a seamless user experience with fast, interactive UIs.

    Mobile Applications: With React Native, which allows developers to build native mobile apps using React.

    Web Applications: Any web application requiring a dynamic, high-performing user interface.