Commit d536cf75 by rahimie-hub

first commit

parent 559e853c
# Getting Started with Create React App
This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app). # my-product-management-system
## Objective:
By the end of this session, students will be able to create class and functional components, style components using CSS, and perform CRUD operations in React using MockAPI. The project will be named "my-product-management-system" and will include pages to register categories and products.
## Agenda:
### 1. Introduction (30 minutes)
- Overview of React components: class components vs functional components.
- Introduction to React's component lifecycle methods.
- Brief introduction to CSS in React.
- Introduction to MockAPI for CRUD operations.
### 2. Setting Up the Project (30 minutes)
- Create a new React project using Create React App.
- Start the React development server.
- Brief overview of the project's folder structure.
\`\`\`bash
npx create-react-app my-product-management-system
cd my-product-management-system
npm start
\`\`\`
\`\`\`
my-product-management-system/
├── public/
│ ├── index.html
│ └── ...
├── src/
│ ├── components/
│ │ ├── Category/
│ │ │ ├── CategoryListClass.js
│ │ │ ├── CategoryFormClass.js
│ │ │ ├── CategoryListFunction.js
│ │ │ ├── CategoryFormFunction.js
│ │ │ ├── Category.css
│ │ ├── Product/
│ │ │ ├── ProductListClass.js
│ │ │ ├── ProductFormClass.js
│ │ │ ├── ProductListFunction.js
│ │ │ ├── ProductFormFunction.js
│ │ │ ├── Product.css
│ ├── services/
│ │ ├── ApiCategory.js
│ │ ├── ApiProduct.js
│ ├── App.js
│ ├── index.js
│ └── ...
├── package.json
└── ...
\`\`\`
### 3. Editing App.js (15 minutes)
- Modify \`App.js\` to include a welcome message and links to the category and product registration pages.
\`\`\`jsx
import React from 'react';
import { BrowserRouter as Router, Route, Link } from 'react-router-dom';
import CategoryFormClass from './components/Category/CategoryFormClass';
import ProductFormClass from './components/Product/ProductFormClass';
function App() {
return (
<Router>
<div className="App">
<h1>Product Management System</h1>
</div>
</Router>
);
}
export default App;
\`\`\`
### 4. Creating Class Components (60 minutes)
- Deep dive into creating class components.
- Create `CategoryFormClass.js` and `CategoryListClass.js` as class components.
- Discuss state management, event handling, and lifecycle methods.
\`\`\`jsx
// CategoryFormClass.js
import React, { Component } from 'react';
import { createCategory } from '../../services/ApiCategory';
class CategoryFormClass extends Component {
state = {
name: '',
description: ''
};
handleChange = (event) => {
this.setState({ [event.target.name]: event.target.value });
};
handleSubmit = async (event) => {
event.preventDefault();
const { name, description } = this.state;
await createCategory({ name, description });
this.setState({ name: '', description: '' });
this.props.fetchCategories();
};
render() {
const { name, description } = this.state;
return (
<form onSubmit={this.handleSubmit}>
<input
type="text"
name="name"
value={name}
onChange={this.handleChange}
placeholder="Category Name"
/>
<input
type="text"
name="description"
value={description}
onChange={this.handleChange}
placeholder="Category Description"
/>
<button type="submit">Add Category</button>
</form>
);
}
}
export default CategoryFormClass;
\`\`\`
\`\`\`jsx
// CategoryListClass.js
import React, { Component } from 'react';
import CategoryFormClass from './CategoryFormClass';
import { getCategories, deleteCategory, updateCategory } from '../../services/ApiCategory';
import './Category.css';
class CategoryListClass extends Component {
state = {
categories: [],
isEditing: false,
currentCategory: { id: '', name: '', description: '' },
};
componentDidMount() {
this.fetchCategories();
}
fetchCategories = async () => {
const categories = await getCategories();
this.setState({ categories });
};
handleDelete = async (id) => {
await deleteCategory(id);
this.fetchCategories();
};
handleEdit = (category) => {
this.setState({ isEditing: true, currentCategory: category });
};
handleCancelEdit = () => {
this.setState({ isEditing: false, currentCategory: { id: '', name: '', description: '' } });
};
handleChange = (event) => {
const { name, value } = event.target;
this.setState((prevState) => ({
currentCategory: { ...prevState.currentCategory, [name]: value }
}));
};
handleUpdate = async (event) => {
event.preventDefault();
const { currentCategory } = this.state;
await updateCategory(currentCategory.id, { name: currentCategory.name, description: currentCategory.description });
this.setState({ isEditing: false, currentCategory: { id: '', name: '', description: '' } });
this.fetchCategories();
};
render() {
const { categories, isEditing, currentCategory } = this.state;
return (
<div>
<h2>Categories</h2>
{isEditing ? (
<form onSubmit={this.handleUpdate}>
<input
type="text"
name="name"
value={currentCategory.name}
onChange={this.handleChange}
placeholder="Category Name"
/>
<input
type="text"
name="description"
value={currentCategory.description}
onChange={this.handleChange}
placeholder="Category Description"
/>
<button type="submit" className="button button-update">Update</button>
<button type="button" className="button button-delete" onClick={this.handleCancelEdit}>Cancel</button>
</form>
) : (
<CategoryFormClass fetchCategories={this.fetchCategories} />
)}
<table>
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Description</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
{categories.map(category => (
<tr key={category.id}>
<td>{category.id}</td>
<td>{category.name}</td>
<td>{category.description}</td>
<td>
<button className="button button-update" onClick={() => this.handleEdit(category)}>Edit</button>
<button className="button button-delete" onClick={() => this.handleDelete(category.id)}>Delete</button>
</td>
</tr>
))}
</tbody>
</table>
</div>
);
}
}
export default CategoryListClass;
\`\`\`
### 5. Creating Functional Components (60 minutes)
- Deep dive into creating functional components with hooks.
- Create `CategoryFormFunction.js` and `CategoryListFunction.js` as functional components.
- Discuss useState and useEffect hooks.
\`\`\`jsx
// CategoryFormFunction.js
import React, { useState } from 'react';
import { createCategory } from '../../services/ApiCategory';
const CategoryFormFunction = ({ fetchCategories }) => {
const [categoryName, setCategoryName] = useState('');
const [description, setDescription] = useState('');
const handleChange = (event) => {
const { name, value } = event.target;
if (name === 'name') setCategoryName(value);
if (name === 'description') setDescription(value);
};
const handleSubmit = async (event) => {
event.preventDefault();
await createCategory({ name: categoryName, description });
setCategoryName('');
setDescription('');
fetchCategories();
};
return (
<form onSubmit={handleSubmit}>
<input
type="text"
name="name"
value={categoryName}
onChange={handleChange}
placeholder="Category Name"
/>
<input
type="text"
name="description"
value={description}
onChange={handleChange}
placeholder="Category Description"
/>
<button type="submit">Add Category</button>
</form>
);
};
export default CategoryFormFunction;
\`\`\`
\`\`\`jsx
// CategoryListFunction.js
import React, { useEffect, useState } from 'react';
import { getCategories, deleteCategory, updateCategory } from '../../services/ApiCategory';
import './Category.css';
import CategoryFormFunction from './CategoryFormFunction';
const CategoryListFunction = () => {
const [categories, setCategories] = useState([]);
const [isEditing, setIsEditing] = useState(false);
const [currentCategory, setCurrentCategory] = useState({ id: '', name: '', description: '' });
useEffect(() => {
fetchCategories();
}, []);
const fetchCategories = async () => {
const categories = await getCategories();
setCategories(categories);
};
const handleDelete = async (id) => {
await deleteCategory(id);
fetchCategories();
};
const handleEdit = (category) => {
setIsEditing(true);
setCurrentCategory(category);
};
const handleCancelEdit = () => {
setIsEditing(false);
setCurrentCategory({ id: '', name: '', description: '' });
};
const handleChange = (event) => {
const { name, value } = event.target;
setCurrentCategory((prevCategory) => ({
...prevCategory,
[name]: value,
}));
};
const handleUpdate = async (event) => {
event.preventDefault();
await updateCategory(currentCategory.id, {
name: currentCategory.name,
description: currentCategory.description,
});
setIsEditing(false);
setCurrentCategory({ id: '', name: '', description: '' });
fetchCategories();
};
return (
<div>
<h2>Categories</h2>
{isEditing ? (
<form onSubmit={handleUpdate}>
<input
type="text"
name="name"
value={currentCategory.name}
onChange={handleChange}
placeholder="Category Name"
/>
<input
type="text"
name="description"
value={currentCategory.description}
onChange={handleChange}
placeholder="Category Description"
/>
<button type="submit" className="button button-update">
Update
</button>
<button type="button" className="button button-delete" onClick={handleCancelEdit}>
Cancel
</button>
</form>
) : (
<CategoryFormFunction fetchCategories={fetchCategories} />
)}
<table>
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Description</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
{categories.map((category) => (
<tr key={category.id}>
<td>{category.id}</td>
<td>{category.name}</td>
<td>{category.description}</td>
<td>
<button className="button button-update" onClick={() => handleEdit(category)}>
Edit
</button>
<button className="button button-delete" onClick={() => handleDelete(category.id)}>
Delete
</button>
</td>
</tr>
))}
</tbody>
</table>
</div>
);
};
export default CategoryListFunction;
\`\`\`
### 6. Lunch Break (30 minutes)
### 7. Adding CSS (30 minutes)
- Demonstrate how to add and apply CSS in React.
- Style the category and product forms.
\`\`\`css
/* Category.css */
form {
margin: 20px;
}
input {
margin-right: 10px;
}
\`\`\`
### 8. Integrating MockAPI for CRUD Operations (60 minutes)
- Set up MockAPI for category and product management.
- Perform CRUD operations (Create, Read, Update, Delete) using MockAPI.
\`\`\`jsx
// ApiCategory.js
const apiUrl = 'https://mockapi.io/endpoint';
export const getCategories = () => fetch(apiUrl).then((res) => res.json());
export const createCategory = (category) =>
fetch(apiUrl, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(category),
}).then((res) => res.json());
export const deleteCategory = (id) =>
fetch(\`\${apiUrl}/\${id}\`, {
method: 'DELETE',
}).then((res) => res.json());
export const updateCategory = (id, category) =>
fetch(\`\${apiUrl}/\${id}\`, {
method: 'PUT',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(category),
}).then((res) => res.json());
\`\`\`
### 9. Building Pages for Category and Product Registration (60 minutes)
- Create forms for category and product registration.
- Link forms to MockAPI for data submission.
\`\`\`jsx
// Example form structure with API integration
const handleSubmit = (event) => {
event.preventDefault();
createCategory({ name: categoryName, description }).then((data) => console.log(data));
};
return (
<form onSubmit={handleSubmit}>
<input type="text" placeholder="Enter category name" />
<button type="submit">Submit</button>
</form>
);
\`\`\`
- Implement similar logic for \`ProductForm.js\`.
### 10. Building Lists to Display Data (45 minutes)
- Create lists to display categories and products.
- Fetch data from MockAPI and render it in the components.
\`\`\`jsx
// CategoryListFunction.js
import React, { useEffect, useState } from 'react';
import { getCategories } from '../services/ApiCategory';
const CategoryListFunction = () => {
const [categories, setCategories] = useState([]);
useEffect(() => {
getCategories().then((data) => setCategories(data));
}, []);
return (
<div>
<h2>Category List</h2>
<ul>
{categories.map((category) => (
<li key={category.id}>{category.name}</li>
))}
</ul>
</div>
);
};
export default CategoryListFunction;
\`\`\`
- Implement similar logic for \`ProductList.js\`.
### 11. Routing Navigation (15 minutes)
- Modify \`App.js\` to include a welcome message and links to the category and product registration pages.
#### Step-by-Step Instructions:
1. **Install React Router:**
- Run the following command to install React Router:
\`\`\`bash
npm install react-router-dom
\`\`\`
2. **Modify App.js:**
- Replace the content of \`App.js\` with the following code:
\`\`\`jsx
import React from 'react';
import { BrowserRouter as Router, Route, Link } from 'react-router-dom';
import logo from './logo.svg';
import './App.css';
import CategoryListClass from './components/Category/CategoryListClass';
import CategoryFormClass from './components/Category/CategoryFormClass';
import CategoryListFunction from './components/Category/CategoryListFunction';
function App() {
return (
<Router>
<div className="App">
<h1>Product Management System</h1>
<nav>
<ul>
<li>
<Link to="/category">Register Category</Link>
</li>
<li>
<Link to="/product">Register Product</Link>
</li>
</ul>
</nav>
<Route path="/category" component={CategoryFormClass} />
<Route path="/product" component={CategoryListFunction} />
</div>
</Router>
);
}
export default App;
\`\`\`
### 13. Design Content Navigation (15 minutes)
- Modify \`App.js\` to include a welcome message and links to the category and product registration pages.
#### Step-by-Step Instructions:
1. **Modify App.js:**
- Replace the content of \`App.js\` with the following code:
\`\`\`jsx
import React from 'react';
import { BrowserRouter as Router, Route, Link } from 'react-router-dom';
import logo from './logo.svg';
import './App.css';
import CategoryListClass from './components/Category/CategoryListClass';
import CategoryFormClass from './components/Category/CategoryFormClass';
import CategoryListFunction from './components/Category/CategoryListFunction';
function App() {
return (
<Router>
<div className="App">
<h1>Product Management System</h1>
<div className="container">
<nav className="sidebar">
<ul>
<li>
<Link to="/category">Register Category</Link>
</li>
<li>
<Link to="/product">Register Product</Link>
</li>
</ul>
</nav>
<div className="content">
<Routes>
<Route path="/category" element={<CategoryListClass />} />
<Route path="/product" element={<CategoryListFunction />} />
</Routes>
</div>
</div>
</div>
</Router>
);
}
export default App;
\`\`\`
2. **Modify App.css:**
- Update to add the content of \`App.css\` with the following code:
\`\`\`css
.App {
font-family: sans-serif;
text-align: center;
}
.container {
display: flex;
height: 100vh;
}
.sidebar {
width: 200px;
background-color: #f8f9fa;
padding: 15px;
box-shadow: 2px 0 5px rgba(0, 0, 0, 0.1);
}
.sidebar ul {
list-style-type: none;
padding: 0;
}
.sidebar ul li {
margin: 10px 0;
}
.sidebar ul li a {
text-decoration: none;
color: #007bff;
font-weight: bold;
}
.content {
flex-grow: 1;
padding: 20px;
}
h1 {
margin: 20px;
}
\`\`\`
## Conclusion (15 minutes)
- Recap the key concepts covered.
- Q&A session to address any doubts or questions.
- Provide resources for further learning.
## Resources:
- [React Documentation](https://reactjs.org/docs/getting-started.html)
- [MockAPI Documentation](https://mockapi.io/docs)
- [CSS Tricks](https://css-tricks.com/)
- [React Router Documentation](https://reactrouter.com/web/guides/quick-start)
- [Redux Documentation](https://redux.js.org/)
### Advanced Topics
- Discuss state management with Context API.
- 3rd-Party libary like axios,sweertalert,formik,bootstrap/tailwind
- Implementing more complex forms and validation.
- Error handling and debugging tips.
This comprehensive 5-hour training module ensures that students gain an in-depth understanding of React components, styling, and CRUD operations, with ample time for hands-on practice and advanced topics.
## Available Scripts
In the project directory, you can run:
### `npm start`
Runs the app in the development mode.\
Open [http://localhost:3000](http://localhost:3000) to view it in your browser.
The page will reload when you make changes.\
You may also see any lint errors in the console.
### `npm test`
Launches the test runner in the interactive watch mode.\
See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information.
### `npm run build`
Builds the app for production to the `build` folder.\
It correctly bundles React in production mode and optimizes the build for the best performance.
The build is minified and the filenames include the hashes.\
Your app is ready to be deployed!
See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information.
### `npm run eject`
**Note: this is a one-way operation. Once you `eject`, you can't go back!**
If you aren't satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project.
Instead, it will copy all the configuration files and the transitive dependencies (webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point you're on your own.
You don't have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldn't feel obligated to use this feature. However we understand that this tool wouldn't be useful if you couldn't customize it when you are ready for it.
## Learn More
You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started).
To learn React, check out the [React documentation](https://reactjs.org/).
### Code Splitting
This section has moved here: [https://facebook.github.io/create-react-app/docs/code-splitting](https://facebook.github.io/create-react-app/docs/code-splitting)
### Analyzing the Bundle Size
This section has moved here: [https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size](https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size)
### Making a Progressive Web App
This section has moved here: [https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app](https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app)
### Advanced Configuration
This section has moved here: [https://facebook.github.io/create-react-app/docs/advanced-configuration](https://facebook.github.io/create-react-app/docs/advanced-configuration)
### Deployment
This section has moved here: [https://facebook.github.io/create-react-app/docs/deployment](https://facebook.github.io/create-react-app/docs/deployment)
### `npm run build` fails to minify
This section has moved here: [https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify](https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify)
...@@ -8,6 +8,7 @@ ...@@ -8,6 +8,7 @@
"@testing-library/user-event": "^13.5.0", "@testing-library/user-event": "^13.5.0",
"react": "^18.3.1", "react": "^18.3.1",
"react-dom": "^18.3.1", "react-dom": "^18.3.1",
"react-router-dom": "^6.26.0",
"react-scripts": "5.0.1", "react-scripts": "5.0.1",
"web-vitals": "^2.1.4" "web-vitals": "^2.1.4"
}, },
......
...@@ -36,3 +36,53 @@ ...@@ -36,3 +36,53 @@
transform: rotate(360deg); transform: rotate(360deg);
} }
} }
.App {
font-family: sans-serif;
text-align: center;
display: flex;
flex-direction: column;
height: 100vh;
}
.topbar {
background-color: #f8f9fa;
box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
padding: 20px;
}
.container {
display: flex;
flex-grow: 1;
}
.sidebar {
width: 200px;
background-color: #f8f9fa;
padding: 15px;
box-shadow: 2px 0 5px rgba(0, 0, 0, 0.1);
text-align: left;
}
.sidebar ul {
list-style-type: none;
padding: 0;
}
.sidebar ul li {
margin: 10px 0;
}
.sidebar ul li a {
text-decoration: none;
color: #007bff;
font-weight: bold;
}
.content {
flex-grow: 1;
padding: 40px;
}
import logo from './logo.svg'; import logo from './logo.svg';
import './App.css'; import './App.css';
import CategoryListClass from './components/Category/CategoryListClass';
import CategoryListFunction from './components/Category/CategoryListFunction';
import { BrowserRouter as Router, Link, Route, Routes } from 'react-router-dom';
import ProductList from './components/Product/ProductList';
function App() { function App() {
return ( return (
<div className="App"> <Router>
<header className="App-header"> <div className="App">
<img src={logo} className="App-logo" alt="logo" /> <div className="topbar">
<p> <h1>Product Management System</h1>
Edit <code>src/App.js</code> and save to reload. </div>
</p> <div className="container">
<a <nav className="sidebar">
className="App-link" <ul>
href="https://reactjs.org" <li>
target="_blank" <Link to="/category1">Category Class</Link>
rel="noopener noreferrer" </li>
> <li>
Learn React <Link to="/category2">Category Functional</Link>
</a> </li>
</header> <li>
</div> <Link to="/product">Product</Link>
</li>
</ul>
</nav>
<div className="content">
<Routes>
<Route path="/category1" element={<CategoryListClass />} />
<Route path="/category2" element={<CategoryListFunction />} />
<Route path="/product" element={<ProductList />} />
</Routes>
</div>
</div>
</div>
</Router>
); );
} }
......
table {
width: 100%;
border-collapse: collapse;
margin: 20px 0;
font-size: 18px;
text-align: left;
}
th, td {
padding: 12px 15px;
border: 1px solid #ddd;
}
th {
background-color: #f4f4f4;
}
tr:nth-child(even) {
background-color: #f9f9f9;
}
tr:hover {
background-color: #f1f1f1;
}
.button {
color: white;
border: none;
padding: 5px 10px;
cursor: pointer;
}
.button-delete {
background-color: #ff4d4d;
}
.button-delete:hover {
background-color: #ff1a1a;
}
.button-update {
background-color:blue;
}
.button-update:hover {
background-color: blue;
}
\ No newline at end of file
import React, { Component } from 'react';
import { createCategory } from '../../services/ApiCategory';
class CategoryFormClass extends Component {
state = {
name: '',
description: ''
};
handleChange = (event) => {
this.setState({ [event.target.name]: event.target.value });
};
handleSubmit = async (event) => {
event.preventDefault();
const { name, description } = this.state;
await createCategory({ name: name, description });
this.setState({ name: '', description: '' });
this.props.fetchCategories();
};
render() {
const { name, description } = this.state;
return (
<form onSubmit={this.handleSubmit}>
<input
type="text"
name="name"
value={name}
onChange={this.handleChange}
placeholder="Category Name"
/>
<input
type="text"
name="description"
value={description}
onChange={this.handleChange}
placeholder="Category Description"
/>
<button type="submit">Add Category</button>
</form>
);
}
}
export default CategoryFormClass;
// CategoryFormFunction.js
import React, { useState } from 'react';
import { createCategory } from '../../services/ApiCategory';
const CategoryFormFunction = ({ fetchCategories }) => {
const [categoryName, setCategoryName] = useState('');
const [description, setDescription] = useState('');
const handleChange = (event) => {
const { name, value } = event.target;
if (name === 'name') setCategoryName(value);
if (name === 'description') setDescription(value);
};
const handleSubmit = async (event) => {
event.preventDefault();
await createCategory({ name: categoryName, description });
setCategoryName('');
setDescription('');
fetchCategories();
};
return (
<form onSubmit={handleSubmit}>
<input
type="text"
name="name"
value={categoryName}
onChange={handleChange}
placeholder="Category Name"
/>
<input
type="text"
name="description"
value={description}
onChange={handleChange}
placeholder="Category Description"
/>
<button type="submit">Add Category</button>
</form>
);
};
export default CategoryFormFunction;
import React, { Component } from 'react';
import CategoryFormClass from './CategoryFormClass';
import { getCategories, deleteCategory, updateCategory } from '../../services/ApiCategory';
import './Category.css';
class CategoryListClass extends Component {
state = {
categories: [],
isEditing: false,
currentCategory: { id: '', name: '', description: '' },
};
componentDidMount() {
this.fetchCategories();
}
fetchCategories = async () => {
const categories = await getCategories();
this.setState({ categories });
};
handleDelete = async (id) => {
await deleteCategory(id);
this.fetchCategories();
};
handleEdit = (category) => {
this.setState({ isEditing: true, currentCategory: category });
};
handleCancelEdit = () => {
this.setState({ isEditing: false, currentCategory: { id: '', name: '', description: '' } });
};
handleChange = (event) => {
const { name, value } = event.target;
this.setState((prevState) => ({
currentCategory: { ...prevState.currentCategory, [name]: value }
}));
};
handleUpdate = async (event) => {
event.preventDefault();
const { currentCategory } = this.state;
await updateCategory(currentCategory.id, { name: currentCategory.name, description: currentCategory.description });
this.setState({ isEditing: false, currentCategory: { id: '', name: '', description: '' } });
this.fetchCategories();
};
render() {
const { categories, isEditing, currentCategory } = this.state;
return (
<div>
<h2>Categories</h2>
{isEditing ? (
<form onSubmit={this.handleUpdate}>
<input
type="text"
name="name"
value={currentCategory.name}
onChange={this.handleChange}
placeholder="Category Name"
/>
<input
type="text"
name="description"
value={currentCategory.description}
onChange={this.handleChange}
placeholder="Category Description"
/>
<button type="submit" className="button button-update">Update</button>
<button type="button" className="button button-delete" onClick={this.handleCancelEdit}>Cancel</button>
</form>
) : (
<CategoryFormClass fetchCategories={this.fetchCategories} />
)}
<table>
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Description</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
{categories.map(category => (
<tr key={category.id}>
<td>{category.id}</td>
<td>{category.name}</td>
<td>{category.description}</td>
<td>
<button className="button button-update" onClick={() => this.handleEdit(category)}>Edit</button>
<button className="button button-delete" onClick={() => this.handleDelete(category.id)}>Delete</button>
</td>
</tr>
))}
</tbody>
</table>
</div>
);
}
}
export default CategoryListClass;
// CategoryListFunction.js
import React, { useEffect, useState } from 'react';
import { getCategories, deleteCategory, updateCategory } from '../../services/ApiCategory';
import './Category.css';
import CategoryFormFunction from './CategoryFormFunction';
const CategoryListFunction = () => {
const [categories, setCategories] = useState([]);
const [isEditing, setIsEditing] = useState(false);
const [currentCategory, setCurrentCategory] = useState({ id: '', name: '', description: '' });
useEffect(() => {
fetchCategories();
}, []);
const fetchCategories = async () => {
const categories = await getCategories();
setCategories(categories);
};
const handleDelete = async (id) => {
await deleteCategory(id);
fetchCategories();
};
const handleEdit = (category) => {
setIsEditing(true);
setCurrentCategory(category);
};
const handleCancelEdit = () => {
setIsEditing(false);
setCurrentCategory({ id: '', name: '', description: '' });
};
const handleChange = (event) => {
const { name, value } = event.target;
setCurrentCategory((prevCategory) => ({
...prevCategory,
[name]: value,
}));
};
const handleUpdate = async (event) => {
event.preventDefault();
await updateCategory(currentCategory.id, {
name: currentCategory.name,
description: currentCategory.description,
});
setIsEditing(false);
setCurrentCategory({ id: '', name: '', description: '' });
fetchCategories();
};
return (
<div>
<h2>Categories</h2>
{isEditing ? (
<form onSubmit={handleUpdate}>
<input
type="text"
name="name"
value={currentCategory.name}
onChange={handleChange}
placeholder="Category Name"
/>
<input
type="text"
name="description"
value={currentCategory.description}
onChange={handleChange}
placeholder="Category Description"
/>
<button type="submit" className="button button-update">
Update
</button>
<button type="button" className="button button-delete" onClick={handleCancelEdit}>
Cancel
</button>
</form>
) : (
<CategoryFormFunction fetchCategories={fetchCategories} />
)}
<table>
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Description</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
{categories.map((category) => (
<tr key={category.id}>
<td>{category.id}</td>
<td>{category.name}</td>
<td>{category.description}</td>
<td>
<button className="button button-update" onClick={() => handleEdit(category)}>
Edit
</button>
<button className="button button-delete" onClick={() => handleDelete(category.id)}>
Delete
</button>
</td>
</tr>
))}
</tbody>
</table>
</div>
);
};
export default CategoryListFunction;
table {
width: 100%;
border-collapse: collapse;
margin: 20px 0;
font-size: 18px;
text-align: left;
}
th, td {
padding: 12px 15px;
border: 1px solid #ddd;
}
th {
background-color: #f4f4f4;
}
tr:nth-child(even) {
background-color: #f9f9f9;
}
tr:hover {
background-color: #f1f1f1;
}
.button {
color: white;
border: none;
padding: 5px 10px;
cursor: pointer;
}
.button-delete {
background-color: #ff4d4d;
}
.button-delete:hover {
background-color: #ff1a1a;
}
.button-update {
background-color:blue;
}
.button-update:hover {
background-color: blue;
}
\ No newline at end of file
import React, { Component } from 'react';
import { createProduct } from '../../services/ApiProduct';
import { getCategories } from '../../services/ApiCategory';
class ProductForm extends Component {
state = {
name: '',
description: '',
categoryId: '',
categories: [],
};
componentDidMount() {
this.fetchCategories();
}
fetchCategories = async () => {
const categories = await getCategories();
this.setState({ categories });
};
handleChange = (event) => {
this.setState({ [event.target.name]: event.target.value });
};
handleSubmit = async (event) => {
event.preventDefault();
const { name, description, categoryId } = this.state;
await createProduct({ name, description, categoryId });
this.setState({ name: '', description: '', categoryId: '' });
this.props.fetchProducts();
};
render() {
const { name, description, categoryId, categories } = this.state;
return (
<form onSubmit={this.handleSubmit}>
<input
type="text"
name="name"
value={name}
onChange={this.handleChange}
placeholder="Product Name"
/>
<input
type="text"
name="description"
value={description}
onChange={this.handleChange}
placeholder="Product Description"
/>
<select name="categoryId" value={categoryId} onChange={this.handleChange}>
<option value="">Select Category</option>
{categories.map(category => (
<option key={category.id} value={category.id}>
{category.name}
</option>
))}
</select>
<button type="submit">Add Product</button>
</form>
);
}
}
export default ProductForm;
import React, { Component } from 'react';
import ProductForm from './ProductForm';
import { deleteProduct, updateProduct, getProduct } from '../../services/ApiProduct';
import './Product.css';
class ProductList extends Component {
state = {
products: [],
isEditing: false,
currentProduct: { id: '', name: '', description: '' },
};
componentDidMount() {
this.fetchProducts();
}
fetchProducts = async () => {
const products = await getProduct();
this.setState({ products });
};
handleDelete = async (id) => {
await deleteProduct(id);
this.fetchProducts();
};
handleEdit = (product) => {
this.setState({ isEditing: true, currentProduct: product });
};
handleCancelEdit = () => {
this.setState({ isEditing: false, currentProduct: { id: '', name: '', description: '' } });
};
handleChange = (event) => {
const { name, value } = event.target;
this.setState((prevState) => ({
currentProduct: { ...prevState.currentProduct, [name]: value }
}));
};
handleUpdate = async (event) => {
event.preventDefault();
const { currentProduct } = this.state;
await updateProduct(currentProduct.id, { name: currentProduct.name, description: currentProduct.description });
this.setState({ isEditing: false, currentProduct: { id: '', name: '', description: '' } });
this.fetchProducts();
};
render() {
const { products, isEditing, currentProduct } = this.state;
return (
<div>
<h2>Products</h2>
{isEditing ? (
<form onSubmit={this.handleUpdate}>
<input
type="text"
name="name"
value={currentProduct.name}
onChange={this.handleChange}
placeholder="Product Name"
/>
<input
type="text"
name="description"
value={currentProduct.description}
onChange={this.handleChange}
placeholder="Product Description"
/>
<button type="submit" className="button button-update">Update</button>
<button type="button" className="button button-delete" onClick={this.handleCancelEdit}>Cancel</button>
</form>
) : (
<ProductForm fetchProducts={this.fetchProducts} />
)}
<table>
<thead>
<tr>
<th>ID</th>
<th>Category</th>
<th>Name</th>
<th>Description</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
{products.map(product => (
<tr key={product.id}>
<td>{product.id}</td>
<td>{product.category}</td>
<td>{product.name}</td>
<td>{product.description}</td>
<td>
<button className="button button-update" onClick={() => this.handleEdit(product)}>Edit</button>
<button className="button button-delete" onClick={() => this.handleDelete(product.id)}>Delete</button>
</td>
</tr>
))}
</tbody>
</table>
</div>
);
}
}
export default ProductList;
const apiUrl = 'https://66b1b4381ca8ad33d4f4d9c0.mockapi.io/api/v1/category'; // Replace with your MockAPI URL
export const getCategories = async () => {
const response = await fetch(`${apiUrl}`);
return response.json();
};
export const getCategoryById = async (id) => {
const response = await fetch(`${apiUrl}/${id}`);
return response.json();
};
export const createCategory = async (category) => {
await fetch(`${apiUrl}`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(category),
});
};
export const updateCategory = async (id, category) => {
await fetch(`${apiUrl}/${id}`, {
method: 'PUT',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(category),
});
};
export const deleteCategory = async (id) => {
await fetch(`${apiUrl}/${id}`, {
method: 'DELETE',
});
};
const apiUrl = 'https://66b1b4381ca8ad33d4f4d9c0.mockapi.io/api/v1/product'; // Replace with your MockAPI URL
export const getProduct = async () => {
const response = await fetch(`${apiUrl}`);
return response.json();
};
export const getProductById = async (id) => {
const response = await fetch(`${apiUrl}/${id}`);
return response.json();
};
export const createProduct = async (category) => {
await fetch(`${apiUrl}`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(category),
});
};
export const updateProduct = async (id, category) => {
await fetch(`${apiUrl}/${id}`, {
method: 'PUT',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(category),
});
};
export const deleteProduct = async (id) => {
await fetch(`${apiUrl}/${id}`, {
method: 'DELETE',
});
};
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment