React JS - Practicals

Code SubtleCode Subtle
6 min read
  1. Create an application in ReactJS to implement the component life cycle

Program:


// 1. Component Life Cycle (Class Component)
import React, { Component } from 'react';

class LifeCycleDemo extends Component {
  constructor(props) {
    super(props);
    this.state = { count: 0 };
    console.log('Constructor called');
  }

  componentDidMount() {
    console.log('Component did mount');
  }

  componentDidUpdate() {
    console.log('Component did update');
  }

  componentWillUnmount() {
    console.log('Component will unmount');
  }

  incrementCount = () => {
    this.setState({ count: this.state.count + 1 });
  };

  render() {
    console.log('Render method called');
    return (
      <div>
        <h1>Lifecycle Methods</h1>
        <p>Count: {this.state.count}</p>
        <button onClick={this.incrementCount}>Increment</button>
      </div>
    );
  }
}

export default LifeCycleDemo;

Explanation:

  1. constructor():

    • When it runs: It runs once when the component is initialized (before it mounts to the DOM).

    • Console log: "Constructor called"

    • Purpose: To initialize state and bind event handlers.

  2. render():

    • When it runs: It runs after the constructor and before componentDidMount. It also runs every time the state or props change.

    • Console log: "Render method called"

    • Purpose: To return the JSX (HTML) structure for the UI.

  3. componentDidMount():

    • When it runs: It runs only once after the component is mounted to the DOM.

    • Console log: "Component did mount"

    • Purpose: To run side effects, API calls, subscriptions, and DOM manipulation after the component is mounted.

  4. componentDidUpdate():

    • When it runs: It runs every time the state or props are updated and the component is re-rendered.

    • Console log: "Component did update"

    • Purpose: To run side effects after an update (like making API calls based on the updated data).

  5. componentWillUnmount():

    • When it runs: It runs when the component is about to be removed from the DOM.

    • Console log: "Component will unmount"

    • Purpose: To clean up subscriptions, timers, or event listeners.

Example of the console log flow:

  1. Component loads for the first time:

     Constructor called
     Render method called
     Component did mount
    
  2. The user clicks the button to update the state:

     Render method called
     Component did update
    

The component is removed from the DOM:

Component will unmount

  1. Create an application to implement class and functional components in ReactJS

Program:

//ClassComponent.jsx
import { Component } from "react";
class ClassComponent extends Component {
  render() {
    return <h1>This is a Class Component</h1>;
  }
}
export default ClassComponent;
import ClassComponent from "./ClassComponent.jsx";

const Functional = () => {
  return (
    <div>
      <ClassComponent />
      <h2>This is Functional Component</h2>
    </div>
  );
};

export default Functional;
import { createRoot } from "react-dom/client";
import Functional from "./Functional";

createRoot(document.getElementById("root")).render(<Functional />);

  1. Create an application in ReactJS to import and export the files (components)

Program:

// File: Header.js
export const Header = () => {
  return (
    <header>
      <h1>Header Component</h1>
      <nav>
        <a href="/home">Home</a> | <a href="/about">About</a> | <a href="/contact">Contact</a>
      </nav>
    </header>
  );
};
// File: Footer.js
export const Footer = () => {
  return (
    <footer>
      <p>© 2024 Your Company</p>
    </footer>
  );
};
// File: App.js
import React from 'react';
import { Header } from './Header';
import { Footer } from './Footer';

function App() {
  return (
    <div>
      <Header />
      <main>
        <h1>Welcome to Our Website</h1>
        <p>This is the main content area.</p>
      </main>
      <Footer />
    </div>
  );
}

export default App;

  1. Create an application to implement state and props

Program:

//ParentComponent.jsx
import  { useState } from "react";
import ChildComponent from "./ChildComponent";

const ParentComponent = () => {
  const [userName, setUserName] = useState("Vitthal");

  const changeUserName = () => {
    setUserName("Korvan");
  };

  return (
    <div>
      <h1>Welcome, {userName}!</h1>
      <ChildComponent name={userName} />
      <button onClick={changeUserName}>Change User Name</button>
    </div>
  );
};

export default ParentComponent;
//ChildComponent
const ChildComponent = ( { name } ) => {
  return <h2>Message is: Hello, {name}!</h2>;
};

export default ChildComponent;
//Main.jsx
import { createRoot } from "react-dom/client";
import ParentComponent from "./ParentComponent";

createRoot(document.getElementById("root")).render(<ParentComponent />);

  1. Create an application in ReactJS to use DOM events

Program:

//App.jsx
import React from "react";

const App = () => {
  function handleClick() {
    alert("Button clicked!");
  }

  function handleInputChange(event) {
    console.log("Input value:", event.target.value);
  }

  function handleFocus() {
    console.log("Input focused");
  }

  return (
    <>
      <input type="text" onChange={handleInputChange} />
      <input type="text" onFocus={handleFocus} />
      <button onClick={handleClick}>Click Me</button>
    </>
  );
};

export default App;
//Main.jsx
import { StrictMode } from "react";
import { createRoot } from "react-dom/client";

import App from "./App.jsx";

createRoot(document.getElementById("root")).render(
  <StrictMode>
    <App />
  </StrictMode>
);

  1. Create an application in ReactJS form and add client and server-side validation

Program:

//FormValidation.jsx
import { useState } from "react";

const FormValidation = () => {
  const [email, setEmail] = useState("");
  const [error, setError] = useState("");

  const validateEmail = (email) => {
    const regex = /^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$/g;
    return regex.test(email);
  };

  const handleSubmit = (e) => {
    e.preventDefault();
    if (!validateEmail(email)) {
      setError("Invalid email address");
    } else {
      setError("");
      alert("Form submitted successfully");
    }
  };

  return (
    <form onSubmit={handleSubmit}>
      <label>Email:</label>
      <input
        type="text"
        value={email}
        onChange={(e) => setEmail(e.target.value)}
      />
      {error && <p style={{ color: "red" }}>{error}</p>}
      <button type="submit">Submit</button>
    </form>
  );
};

export default FormValidation;
//Main.jsx
import { StrictMode } from 'react'
import { createRoot } from 'react-dom/client'
import FormValidation from './FormValidation.jsx'

createRoot(document.getElementById('root')).render(
  <StrictMode>
    <FormValidation />
  </StrictMode>,
)

  1. Create an application to implement React Hooks

Program:

//HooksDemo.jsx
import { useState, useEffect } from "react";

const HooksDemo = () => {
  const [count, setCount] = useState(0);

  useEffect(() => {
    console.log("Component mounted or count updated");
    return () => {
      console.log("Cleanup on component unmount");
    };
  }, [count]);

  return (
    <div>
      <h1>Count: {count}</h1>
      <button onClick={() => setCount(count + 1)}>Increment</button>
    </div>
  );
};

export default HooksDemo;
//Main.jsx
import { StrictMode } from 'react'
import { createRoot } from 'react-dom/client'
import HooksDemo from './HooksDemo.jsx'

createRoot(document.getElementById('root')).render(
  <StrictMode>
    <HooksDemo />
  </StrictMode>,
)

  1. Create SPA using React Router

npm install react-router-dom

Program:

//Home.jsx
const Home = () => {
  return (
    <div>
      <h1>Welcome to Home Page</h1>
      <p>This is the home page of our single-page application.</p>
    </div>
  );
};

export default Home;
//About.jsx
const About = () => {
  return (
    <div>
      <h1>Welcome to About Page</h1>
      <p>This is the About page of our single-page application.</p>
    </div>
  );
};

export default About;
//Contact.jsx
const Contact = () => {
  return (
    <div>
      <h1>Contact Us</h1>
      <p>Feel free to contact us via the form below.</p>
    </div>
  );
};

export default Contact;
//App.jsx
import { BrowserRouter as Router, Routes, Route, Link } from "react-router-dom";
import Home from "./components/Home";
import About from "./components/About";
import Contact from "./components/Contact";

const App = () => {
  return (
    <Router>
      <nav>
        <ul>
          <li>
            <Link to="/">Home</Link>
          </li>
          <li>
            <Link to="/about">About</Link>
          </li>
          <li>
            <Link to="/contact">Contact</Link>
          </li>
        </ul>
      </nav>

      <Routes>
        <Route path="/" element={<Home />} />
        <Route path="/about" element={<About />} />
        <Route path="/contact" element={<Contact />} />
      </Routes>
    </Router>
  );
};

export default App;
//Main.jsx

import { StrictMode } from 'react'
import { createRoot } from 'react-dom/client'
import App from './App.jsx'

createRoot(document.getElementById('root')).render(
  <StrictMode>
    <App />
  </StrictMode>,
)
0
Subscribe to my newsletter

Read articles from Code Subtle directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Code Subtle
Code Subtle

At Code Subtle, we empower aspiring web developers through personalized mentorship and engaging learning resources. Our community bridges the gap between theory and practice, guiding students from basics to advanced concepts. We offer expert mentorship and write interactive, user-friendly articles on all aspects of web development. Join us to learn, grow, and build your future in tech!