Sure! Let's build a React application for managing warehouse entities with the specified requirements. We'll use the following technologies:
- React
- React Hook Form for form handling
- Yup for form validation
- Axios for HTTP requests
- Vite for the frontend build tool
- Express for the backend server
Below is a step-by-step guide along with code snippets to help you create the application.
Project Setup
Frontend Setup with Vite
-
Initialize the Vite project:
npm create vite@latest warehouse-manager -- --template react
cd warehouse-manager
npm install
-
Install dependencies:
npm install react-hook-form yup @hookform/resolvers axios
Backend Setup with Express
-
Initialize the backend project:
mkdir server
cd server
npm init -y
npm install express cors
-
Create the server file index.js:
import express from 'express';
import cors from 'cors';
const app = express();
const PORT = 5000;
app.use(cors());
app.use(express.json());
let entities = [
// Predefined default values
{
id: 1,
name: 'Item 1',
type: 'Type A',
quantity: 100,
// Additional fields...
},
// Add more entities as needed
];
// Routes will be added here
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});
-
Add API routes:
// Get all entities
app.get('/entities', (req, res) => {
res.json(entities);
});
// Create a new entity
app.post('/entities', (req, res) => {
const newEntity = { id: Date.now(), ...req.body };
entities.push(newEntity);
res.status(201).json(newEntity);
});
// Update an existing entity
app.patch('/entities/:id', (req, res) => {
const { id } = req.params;
const index = entities.findIndex((e) => e.id == id);
if (index !== -1) {
entities[index] = { ...entities[index], ...req.body };
res.json(entities[index]);
} else {
res.status(404).json({ message: 'Entity not found' });
}
});
-
Run the server:
node index.js
Frontend Development
Directory Structure
src/
├── components/
│ ├── EntityForm.jsx
│ └── EntityList.jsx
├── App.jsx
└── main.jsx
Creating the Entity List Page
EntityList.jsx
import React, { useEffect, useState } from 'react';
import axios from 'axios';
import { useNavigate } from 'react-router-dom';
export function EntityList() {
const [entities, setEntities] = useState([]);
const navigate = useNavigate();
useEffect(() => {
axios.get('http://localhost:5000/entities').then((response) => {
setEntities(response.data);
});
}, []);
const handleEdit = (id) => {
navigate(`/edit/${id}`);
};
return (
<div>
<h1>Entity List</h1>
<button onClick={() => navigate('/create')}>Create Entity</button>
<table>
<thead>
<tr>
<th>Name</th>
<th>Type</th>
<th>Quantity</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
{entities.map((entity) => (
<tr key={entity.id}>
<td>{entity.name}</td>
<td>{entity.type}</td>
<td>{entity.quantity}</td>
<td>
<button onClick={() => handleEdit(entity.id)}>Edit</button>
</td>
</tr>
))}
</tbody>
</table>
</div>
);
}
Creating the Entity Form Component
EntityForm.jsx
import React, { useEffect } from 'react';
import { useForm, useFieldArray, Controller } from 'react-hook-form';
import { useNavigate, useParams } from 'react-router-dom';
import axios from 'axios';
import { yupResolver } from '@hookform/resolvers/yup';
import * as yup from 'yup';
export function EntityForm({ isEdit = false }) {
const { id } = useParams();
const navigate = useNavigate();
// Validation schema
const schema = yup.object().shape({
name: yup.string().required('Name is required'),
description: yup.string().max(255, 'Description is too long'),
type: yup.string().required('Type is required'),
// Add other validations...
});
const {
register,
control,
handleSubmit,
setValue,
watch,
formState: { errors },
} = useForm({
resolver: yupResolver(schema),
defaultValues: {
tasks: [{ name: '', status: '' }],
},
});
const { fields, append, remove } = useFieldArray({
control,
name: 'tasks',
});
const onSubmit = (data) => {
const endpoint = isEdit
? `http://localhost:5000/entities/${id}`
: 'http://localhost:5000/entities';
const method = isEdit ? 'patch' : 'post';
// Filter out unfilled fields for create
const payload = Object.fromEntries(
Object.entries(data).filter(([_, v]) => v !== '' && v !== undefined)
);
// For edit, include only changed fields
if (isEdit) {
// Implement logic to include only changed fields
}
axios[method](endpoint, payload).then(() => {
navigate('/');
});
};
// Load existing entity data for editing
useEffect(() => {
if (isEdit) {
axios.get(`http://localhost:5000/entities/${id}`).then((response) => {
const data = response.data;
// Set form values
for (const key in data) {
setValue(key, data[key]);
}
});
}
}, [id, isEdit, setValue]);
// Watch radio button to control additional inputs
const showAdditionalFields = watch('radioOption') === 'yes';
return (
<form onSubmit={handleSubmit(onSubmit)}>
<h1>{isEdit ? 'Edit Entity' : 'Create Entity'}</h1>
<div className="grid-container">
{/* Name Input */}
<div>
<label>Name *</label>
<input {...register('name')} />
{errors.name && <p className="error">{errors.name.message}</p>}
</div>
{/* Description Input */}
<div>
<label>Description</label>
<input {...register('description')} />
{errors.description && (
<p className="error">{errors.description.message}</p>
)}
</div>
{/* Type Select */}
<div>
<label>Type *</label>
<select {...register('type')}>
<option value="">Select type</option>
<option value="Type A">Type A</option>
<option value="Type B">Type B</option>
</select>
{errors.type && <p className="error">{errors.type.message}</p>}
</div>
{/* Quantity Input */}
<div>
<label>Quantity</label>
<input type="number" {...register('quantity')} />
</div>
{/* Radio Button */}
<div>
<label>Include additional info?</label>
<div>
<label>
<input
type="radio"
value="yes"
{...register('radioOption')}
/>{' '}
Yes
</label>
<label>
<input type="radio" value="no" {...register('radioOption')} /> No
</label>
</div>
</div>
{/* Additional Inputs Controlled by Radio Button */}
{showAdditionalFields && (
<>
<div>
<label>Additional Select</label>
<select {...register('additionalSelect')}>
<option value="">Select option</option>
<option value="Option 1">Option 1</option>
</select>
</div>
<div>
<label>Additional Text</label>
<input {...register('additionalText')} />
</div>
</>
)}
{/* Array Inputs for Nested Entities (Tasks) */}
<div>
<label>Tasks</label>
{fields.map((item, index) => (
<div key={item.id}>
<input
placeholder="Task Name"
{...register(`tasks.${index}.name`)}
/>
<select {...register(`tasks.${index}.status`)}>
<option value="">Select status</option>
<option value="Pending">Pending</option>
<option value="Completed">Completed</option>
</select>
<button type="button" onClick={() => remove(index)}>
Remove Task
</button>
</div>
))}
<button type="button" onClick={() => append({})}>
Add Task
</button>
</div>
</div>
<button type="submit">{isEdit ? 'Update' : 'Create'}</button>
</form>
);
}
Note: The grid-container class will use CSS Grid to create a multidimensional layout.
Explanation: Why CSS Grid over Flexbox for Multidimensional Layouts
CSS Grid is specifically designed for two-dimensional layouts, allowing you to control both rows and columns simultaneously. This makes it ideal for forms that need to be organized in a grid-like structure. Flexbox, on the other hand, is optimized for one-dimensional layouts (either row or column). Using CSS Grid makes it easier to align form fields in both directions without complex nesting or additional wrappers.
Adding Styles with CSS Grid
Create a CSS file App.css or include styles in your component:
.grid-container {
display: grid;
grid-template-columns: repeat(2, 1fr); /* Two columns */
gap: 20px;
}
.error {
color: red;
font-size: 12px;
}
Setting Up Routing
App.jsx
import React from 'react';
import { BrowserRouter as Router, Routes, Route } from 'react-router-dom';
import { EntityList } from './components/EntityList';
import { EntityForm } from './components/EntityForm';
export function App() {
return (
<Router>
<Routes>
<Route path="/" element={<EntityList />} />
<Route path="/create" element={<EntityForm />} />
<Route path="/edit/:id" element={<EntityForm isEdit={true} />} />
</Routes>
</Router>
);
}
Main Entry Point
main.jsx
import React from 'react';
import ReactDOM from 'react-dom/client';
import { App } from './App';
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<App />);
Handling Form Submission and Payload Filtering
In the onSubmit function inside EntityForm, we filter the payload to include only the fields that have been filled out.
const onSubmit = (data) => {
const endpoint = isEdit ? `http://localhost:5000/entities/${id}` : 'http://localhost:5000/entities';
const method = isEdit ? 'patch' : 'post';
// Filter out unfilled fields for create
const payload = Object.fromEntries(
Object.entries(data).filter(([_, v]) => v !== '' && v !== undefined)
);
// For edit, include only changed fields
if (isEdit) {
// Implement logic to include only changed fields
// You might need to compare with original data
}
axios[method](endpoint, payload).then(() => {
navigate('/');
});
};
Form Validation with Yup
We've set up validation rules using yup and integrated them with react-hook-form using yupResolver.
const schema = yup.object().shape({
name: yup.string().required('Name is required'),
description: yup.string().max(255, 'Description is too long'),
type: yup.string().required('Type is required'),
// Add other validations...
});
Displaying Inline Error Messages
For each field that has validation, we check for errors and display the error message below the input.
{errors.name && <p className="error">{errors.name.message}</p>}
Final Notes
- ES Modules and Non-default Exports: All modules use ES module syntax (
import/export) and avoid default exports as per the requirements.
- Styling: We use CSS Grid to create the form's multidimensional layout, as it allows for straightforward definition of rows and columns.
- Reusable Components: The
EntityForm component is reused for both creating and editing entities, with the isEdit prop determining its behavior.
- Data Handling: The server stores entities in memory with predefined default values for easier testing and editing.
- Optional Fields and Conditional Inputs: The form includes optional fields and inputs that are conditionally rendered based on the selected radio button.
Running the Application
-
Start the Backend Server:
node server/index.js
-
Start the Frontend Application:
npm run dev
Visit http://localhost:3000 to see the application in action.
Conclusion
We've created a React application with a list page and a create/edit form that meets all the specified requirements. The form includes multiple input types, validation with yup, dynamic fields controlled by a radio button, and the ability to add multiple nested entities. The layout is organized using CSS Grid, which is more suitable than Flexbox for multidimensional layouts due to its ability to handle both rows and columns efficiently.
Feel free to expand upon this foundation to add more features or styles as needed!