Monday, February 17, 2025

React - Create Project

 

what each command does and why it’s used:


Step 1: Create a React Project




npx create-react-app react-todos

  • What it does:

    • npx is a tool that comes with npm (Node Package Manager) to run packages without installing them globally.

    • create-react-app is a tool that sets up a new React project with a default folder structure, configuration, and necessary dependencies.

    • react-todos is the name of your project. You can replace this with any name you like.

  • Why it’s used:

    • create-react-app simplifies the process of setting up a React project by handling all the configuration (e.g., Webpack, Babel) for you.

    • Using npx ensures you’re using the latest version of create-react-app without needing to install it globally.



Step 2: Navigate into the Project Folder


 

 
cd react-todos

  • What it does:

    • cd stands for "change directory."

    • This command moves you into the react-todos folder so you can start working on the project.

  • Why it’s used:

    • After creating the project, you need to navigate into the project folder to run further commands (e.g., installing dependencies, starting the server).



Step 3: Install React Version 18.3.1


 

 
npm install react@18.3.1 react-dom@18.3.1

  • What it does:

    • npm install is used to install packages.

    • react@18.3.1 installs React at version 18.3.1.

    • react-dom@18.3.1 installs React DOM at version 18.3.1 (React DOM is required to render React components in the browser).

  • Why it’s used:

    • By default, create-react-app installs the latest stable version of React. If you need a specific version (e.g., 18.3.1), you must manually install it.



Step 4: Install web-vitals


 

 
npm install web-vitals

  • What it does:

    • Installs the web-vitals package, which is a library for measuring performance metrics in web applications.

  • Why it’s used:

    • web-vitals is often used in React apps to track performance metrics like Largest Contentful Paint (LCP), First Input Delay (FID), and Cumulative Layout Shift (CLS).

    • It’s included by default in create-react-app projects for performance monitoring.



Step 5: Start the Development Server


 

 
npm start

  • What it does:

    • Runs the development server.

    • Opens your React app in the browser (usually at http://localhost:3000).

  • Why it’s used:

    • The development server allows you to see your React app in action and automatically reloads the page when you make changes to the code.



Summary of Commands

Here’s the complete set of commands for easy reference:



 

 
npx create-react-app react-todos
cd react-todos
npm install react@18.3.1 react-dom@18.3.1
npm install web-vitals
npm start


Why These Steps Are Important

  1. npx create-react-app: Sets up a new React project with a standardized structure and configuration.

  2. cd react-todos: Moves you into the project folder to run further commands.

  3. npm install react@18.3.1 react-dom@18.3.1: Ensures you’re using the specific version of React you need.

  4. npm install web-vitals: Adds performance monitoring to your app.

  5. npm start: Starts the development server so you can view and test your app.


Loading React App



1- File: public/index.html

<body>

 <div id=“root”></div>

</body>


2- File: src/index.js

const root = React.DOM.createRoot(

document.getElementById('root')

);

root.render(

  <React.StrictMode>

    <App />

  </React.StrictMode>

);


3- File: src/app.js

return(

<p>We made our first React Application! </p>

)


What is JSX (JavaScript XML)?

JSX (JavaScript XML) is a syntax extension for JavaScript that allows writing HTML-like code inside JavaScript. It is primarily used with React to describe the structure of the user interface in a more readable way.


Why use JSX?

  1. Easier Readability: JSX makes UI components more intuitive and similar to HTML.
  2. Efficient Virtual DOM Updates: React compiles JSX to JavaScript, optimizing updates.
  3. Prevents XSS Attacks: JSX escapes values before rendering to prevent cross-site scripting attacks.
  4. Better Debugging: Since JSX compiles down to JavaScript, errors are easier to debug.
  5. Encapsulation with Components: JSX integrates well with React’s component-based architecture.

Example: JSX vs. Traditional JavaScript

Without JSX (Using React.createElement)


const element = React.createElement"h1", { className"greeting" }, "Hello, JSX!" ); 
ReactDOM.render(element, document.getElementById("root"));
  • This is difficult to read and manage, especially with nested elements.

With JSX


const element = <h1 className="greeting">Hello, JSX!</h1>ReactDOM.render(element, document.getElementById("root"));
  • This is cleaner and looks more like HTML.

How JSX Works Internally

JSX is not native JavaScript; it is compiled to React.createElement calls.
For example:


const element = <h1>Hello, World!</h1>;

Compiles to:


const element = React.createElement("h1"null"Hello, World!");

This means JSX is just syntactic sugar over plain JavaScript function calls.


JSX Expressions and Attributes

JSX allows embedding JavaScript expressions inside {}:


const name = "Alice"
const element = <h1>Hello, {name}!</h1>;

You can also use JavaScript inside attributes:

jsx
const imageUrl = "https://example.com/image.jpg"
const element = <img src={imageUrl} alt="Example Image" />;

JSX Conditional Rendering

Using Ternary Operator

jsx
const isLoggedIn = trueconst message = <h1>{isLoggedIn ? "Welcome back!" : "Please log in."}</h1>;

Using Logical AND (&&)

jsx
const isAdmin = trueconst adminPanel = isAdmin && <button>Admin Panel</button>;

JSX with Components

JSX is mostly used within React components:

jsx
function Welcome(props) { return <h1>Hello, {props.name}!</h1>; } ReactDOM.render(<Welcome name="Alice" />document.getElementById("root"));

Conclusion

JSX simplifies writing React components by making UI code more readable and maintainable. Even though browsers don’t understand JSX directly, it is transpiled to JavaScript using tools like Babel before execution.


Integrate React with Bootstrap

Development Process

1. Get links for remote Bootstrap file

Visit Bootstrap website: www.getbootstrap.com

2. Add links to index.html

<head>

         <!-- Bootstrap CSS -->

         <link rel="stylesheet"                 href="https://cdn.jsdelivr.net/npm/bootstrap@x.y.z/dist/css/bootstrap.min.css" …>

</head

    

     <!-- Bootstrap JS Dependencies -->

     <script src="https://cdn.jsdelivr.net/npm/bootstrap@x.y.z/dist/js/bootstrap.bundle" …>

    

</body


3. Apply Bootstrap CSS styles in component HTML template

<div className=“container">

<div className=“card”> </div>

</div>

4. Apply Bootstrap CSS styles in component HTML table

<table className="table table-hover">



To build a React application (using React 18.3.1) that interacts with your Spring Boot REST API for an Employee Management System, we’ll follow these steps:


Step 1: Set Up the React Project

  1. Create a new React project:


    npx create-react-app employee-management
    cd employee-management
    npm install react@18.3.1 react-dom@18.3.1

  2. Install required dependencies:



    npm install axios react-router-dom bootstrap react-bootstrap
    • axios: For making HTTP requests to your Spring Boot API.

    • react-router-dom: For routing in the React app.

    • bootstrap and react-bootstrap: For styling and UI components.


  3. Add Bootstrap CSS to src/index.js:



    import 'bootstrap/dist/css/bootstrap.min.css';


Step 2: Set Up Routing

Create a Routes component to handle navigation.

  1. Create a file src/Routes.js:



    import { BrowserRouter as Router, Route, Routes } from 'react-router-dom';
    import EmployeeList from './components/EmployeeList';
    import AddEmployee from './components/AddEmployee';
    import EditEmployee from './components/EditEmployee';
    import Login from './components/Login';
    
    const AppRoutes = () => {
      return (
        <Router>
          <Routes>
            <Route path="/" element={<EmployeeList />} />
            <Route path="/add" element={<AddEmployee />} />
            <Route path="/edit/:id" element={<EditEmployee />} />
            <Route path="/login" element={<Login />} />
          </Routes>
        </Router>
      );
    };
    
    export default AppRoutes;

  2. Update src/index.js to use the Routes component:



    import React from 'react';
    import ReactDOM from 'react-dom/client';
    import AppRoutes from './Routes';
    
    const root = ReactDOM.createRoot(document.getElementById('root'));
    root.render(<AppRoutes />);


Step 3: Create Components


1. EmployeeList Component

This component will display a list of employees with search and pagination.

  1. Create src/components/EmployeeList.js:



    import React, { useEffect, useState } from 'react';
    import axios from 'axios';
    import { Table, Pagination, Form, Button, Container } from 'react-bootstrap';
    import { useNavigate } from 'react-router-dom';
    
    const EmployeeList = () => {
      const [employees, setEmployees] = useState([]);
      const [searchTerm, setSearchTerm] = useState('');
      const [page, setPage] = useState(1);
      const [totalPages, setTotalPages] = useState(0);
      const navigate = useNavigate();
    
      useEffect(() => {
        fetchEmployees();
      }, [page, searchTerm]);
    
      const fetchEmployees = async () => {
        try {
          const response = await axios.get(`http://localhost:8080/api/employees?page=${page}&search=${searchTerm}`);
          setEmployees(response.data.content);
          setTotalPages(response.data.totalPages);
        } catch (error) {
          console.error('Error fetching employees:', error);
        }
      };
    
      const handleSearch = (e) => {
        setSearchTerm(e.target.value);
      };
    
      const handlePageChange = (newPage) => {
        setPage(newPage);
      };
    
      return (
        <Container>
          <h1>Employee List</h1>
          <Form.Control
            type="text"
            placeholder="Search by name"
            value={searchTerm}
            onChange={handleSearch}
            className="mb-3"
          />
          <Table striped bordered hover>
            <thead>
              <tr>
                <th>ID</th>
                <th>Name</th>
                <th>Designation</th>
                <th>Salary</th>
                <th>Action</th>
              </tr>
            </thead>
            <tbody>
              {employees.map((employee) => (
                <tr key={employee.empId}>
                  <td>{employee.empId}</td>
                  <td>{employee.empName}</td>
                  <td>{employee.designation}</td>
                  <td>{employee.salary}</td>
                  <td>
                    <Button variant="primary" onClick={() => navigate(`/edit/${employee.empId}`)}>
                      Edit
                    </Button>
                  </td>
                </tr>
              ))}
            </tbody>
          </Table>
          <Pagination>
            {Array.from({ length: totalPages }, (_, index) => (
              <Pagination.Item
                key={index + 1}
                active={index + 1 === page}
                onClick={() => handlePageChange(index + 1)}
              >
                {index + 1}
              </Pagination.Item>
            ))}
          </Pagination>
          <Button variant="success" onClick={() => navigate('/add')}>
            Add Employee
          </Button>
        </Container>
      );
    };
    
    export default EmployeeList;


2. AddEmployee Component

This component will allow adding a new employee.

  1. Create src/components/AddEmployee.js:



    import React, { useState } from 'react';
    import axios from 'axios';
    import { Form, Button, Container } from 'react-bootstrap';
    import { useNavigate } from 'react-router-dom';
    
    const AddEmployee = () => {
      const [employee, setEmployee] = useState({
        empName: '',
        designation: '',
        salary: 0,
        empPhoneNumber: '',
        deptId: 0,
      });
      const navigate = useNavigate();
    
      const handleSubmit = async (e) => {
        e.preventDefault();
        try {
          await axios.post('http://localhost:8080/api/employees', employee);
          navigate('/');
        } catch (error) {
          console.error('Error adding employee:', error);
        }
      };
    
      return (
        <Container>
          <h1>Add Employee</h1>
          <Form onSubmit={handleSubmit}>
            <Form.Group className="mb-3">
              <Form.Label>Name</Form.Label>
              <Form.Control
                type="text"
                value={employee.empName}
                onChange={(e) => setEmployee({ ...employee, empName: e.target.value })}
              />
            </Form.Group>
            <Form.Group className="mb-3">
              <Form.Label>Designation</Form.Label>
              <Form.Control
                type="text"
                value={employee.designation}
                onChange={(e) => setEmployee({ ...employee, designation: e.target.value })}
              />
            </Form.Group>
            <Form.Group className="mb-3">
              <Form.Label>Salary</Form.Label>
              <Form.Control
                type="number"
                value={employee.salary}
                onChange={(e) => setEmployee({ ...employee, salary: e.target.value })}
              />
            </Form.Group>
            <Form.Group className="mb-3">
              <Form.Label>Phone Number</Form.Label>
              <Form.Control
                type="text"
                value={employee.empPhoneNumber}
                onChange={(e) => setEmployee({ ...employee, empPhoneNumber: e.target.value })}
              />
            </Form.Group>
            <Form.Group className="mb-3">
              <Form.Label>Department ID</Form.Label>
              <Form.Control
                type="number"
                value={employee.deptId}
                onChange={(e) => setEmployee({ ...employee, deptId: e.target.value })}
              />
            </Form.Group>
            <Button variant="primary" type="submit">
              Add Employee
            </Button>
          </Form>
        </Container>
      );
    };
    
    export default AddEmployee;


3. EditEmployee Component

This component will allow editing an existing employee.

  1. Create src/components/EditEmployee.js:



    import React, { useEffect, useState } from 'react';
    import axios from 'axios';
    import { Form, Button, Container } from 'react-bootstrap';
    import { useNavigate, useParams } from 'react-router-dom';
    
    const EditEmployee = () => {
      const { id } = useParams();
      const [employee, setEmployee] = useState({
        empName: '',
        designation: '',
        salary: 0,
        empPhoneNumber: '',
        deptId: 0,
      });
      const navigate = useNavigate();
    
      useEffect(() => {
        fetchEmployee();
      }, [id]);
    
      const fetchEmployee = async () => {
        try {
          const response = await axios.get(`http://localhost:8080/api/employees/${id}`);
          setEmployee(response.data);
        } catch (error) {
          console.error('Error fetching employee:', error);
        }
      };
    
      const handleSubmit = async (e) => {
        e.preventDefault();
        try {
          await axios.put(`http://localhost:8080/api/employees/${id}`, employee);
          navigate('/');
        } catch (error) {
          console.error('Error updating employee:', error);
        }
      };
    
      return (
        <Container>
          <h1>Edit Employee</h1>
          <Form onSubmit={handleSubmit}>
            <Form.Group className="mb-3">
              <Form.Label>Name</Form.Label>
              <Form.Control
                type="text"
                value={employee.empName}
                onChange={(e) => setEmployee({ ...employee, empName: e.target.value })}
              />
            </Form.Group>
            <Form.Group className="mb-3">
              <Form.Label>Designation</Form.Label>
              <Form.Control
                type="text"
                value={employee.designation}
                onChange={(e) => setEmployee({ ...employee, designation: e.target.value })}
              />
            </Form.Group>
            <Form.Group className="mb-3">
              <Form.Label>Salary</Form.Label>
              <Form.Control
                type="number"
                value={employee.salary}
                onChange={(e) => setEmployee({ ...employee, salary: e.target.value })}
              />
            </Form.Group>
            <Form.Group className="mb-3">
              <Form.Label>Phone Number</Form.Label>
              <Form.Control
                type="text"
                value={employee.empPhoneNumber}
                onChange={(e) => setEmployee({ ...employee, empPhoneNumber: e.target.value })}
              />
            </Form.Group>
            <Form.Group className="mb-3">
              <Form.Label>Department ID</Form.Label>
              <Form.Control
                type="number"
                value={employee.deptId}
                onChange={(e) => setEmployee({ ...employee, deptId: e.target.value })}
              />
            </Form.Group>
            <Button variant="primary" type="submit">
              Update Employee
            </Button>
          </Form>
        </Container>
      );
    };
    
    export default EditEmployee;


Step 4: JWT Authentication

  1. Add a Login component for JWT authentication.

  2. Use axios interceptors to attach the JWT token to requests.

  3. Protect routes using a PrivateRoute component.



Step 5: Run the Application

  1. Start the Spring Boot backend.

  2. Run the React app:


    npm start

This setup provides a complete React frontend using Bootstrap for your Spring Boot Employee Management System



No comments:

Post a Comment