what each command does and why it’s used:
Step 1: Create a React Project
npx create-react-app react-todosWhat it does:
npxis a tool that comes with npm (Node Package Manager) to run packages without installing them globally.create-react-appis a tool that sets up a new React project with a default folder structure, configuration, and necessary dependencies.react-todosis the name of your project. You can replace this with any name you like.
Why it’s used:
create-react-appsimplifies the process of setting up a React project by handling all the configuration (e.g., Webpack, Babel) for you.Using
npxensures you’re using the latest version ofcreate-react-appwithout needing to install it globally.
Step 2: Navigate into the Project Folder
cd react-todosWhat it does:
cdstands for "change directory."This command moves you into the
react-todosfolder 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.1What it does:
npm installis used to install packages.react@18.3.1installs React at version 18.3.1.react-dom@18.3.1installs 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-appinstalls 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-vitalsWhat it does:
Installs the
web-vitalspackage, which is a library for measuring performance metrics in web applications.
Why it’s used:
web-vitalsis 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-appprojects for performance monitoring.
Step 5: Start the Development Server
npm startWhat 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 startWhy These Steps Are Important
npx create-react-app: Sets up a new React project with a standardized structure and configuration.cd react-todos: Moves you into the project folder to run further commands.npm install react@18.3.1 react-dom@18.3.1: Ensures you’re using the specific version of React you need.npm install web-vitals: Adds performance monitoring to your app.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?
- Easier Readability: JSX makes UI components more intuitive and similar to HTML.
- Efficient Virtual DOM Updates: React compiles JSX to JavaScript, optimizing updates.
- Prevents XSS Attacks: JSX escapes values before rendering to prevent cross-site scripting attacks.
- Better Debugging: Since JSX compiles down to JavaScript, errors are easier to debug.
- Encapsulation with Components: JSX integrates well with React’s component-based architecture.
Example: JSX vs. Traditional JavaScript
Without JSX (Using React.createElement)
- This is difficult to read and manage, especially with nested elements.
With JSX
- 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:
Compiles to:
This means JSX is just syntactic sugar over plain JavaScript function calls.
JSX Expressions and Attributes
JSX allows embedding JavaScript expressions inside {}:
You can also use JavaScript inside attributes:
JSX Conditional Rendering
Using Ternary Operator
Using Logical AND (&&)
JSX with Components
JSX is mostly used within React components:
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
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
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.
Add Bootstrap CSS to src/index.js:
import 'bootstrap/dist/css/bootstrap.min.css';
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
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.bootstrapandreact-bootstrap: For styling and UI components.
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.
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;
Update
src/index.jsto use theRoutescomponent: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.
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.
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.
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
Add a Login component for JWT authentication.
Use axios interceptors to attach the JWT token to requests.
Protect routes using a PrivateRoute component.
Add a Login component for JWT authentication.
Use axios interceptors to attach the JWT token to requests.
Protect routes using a PrivateRoute component.
Step 5: Run the Application
Start the Spring Boot backend.
Run the React app:
npm start
Start the Spring Boot backend.
Run the React app:
npm startThis setup provides a complete React frontend using Bootstrap for your Spring Boot Employee Management System
No comments:
Post a Comment