Here is the complete code for your warehouse management application, built with React, react-hook-form, yup, axios, Vite, and Express. This application meets all your specified requirements and utilizes ES modules without default exports.
Server Setup (Express.js)
First, set up an Express server that stores entities in memory with some predefined data.
server/package.json
{
"name": "server",
"version": "1.0.0",
"description": "",
"main": "index.js",
"type": "module",
"scripts": {
"start": "node index.js"
},
"dependencies": {
"body-parser": "^1.20.2",
"cors": "^2.8.5",
"express": "^4.18.2"
}
}
server/index.js
import express from 'express';
import bodyParser from 'body-parser';
import cors from 'cors';
const app = express();
app.use(cors());
app.use(bodyParser.json());
let entities = [
{
id: 1,
name: 'Item 1',
description: 'Description of Item 1',
category: 'Category A',
status: 'Available',
extraInfo: { field1: 'Extra 1', field2: 'Extra 2' },
tasks: [
{ name: 'Task 1', status: 'Pending' },
{ name: 'Task 2', status: 'Completed' },
],
},
{
id: 2,
name: 'Item 2',
description: 'Description of Item 2',
category: 'Category B',
status: 'Unavailable',
tasks: [{ name: 'Task A', status: 'Pending' }],
},
];
app.get('/api/entities', (req, res) => {
res.json(entities);
});
app.post('/api/entities', (req, res) => {
const newEntity = { id: entities.length + 1, ...req.body };
entities.push(newEntity);
res.json(newEntity);
});
app.put('/api/entities/:id', (req, res) => {
const id = parseInt(req.params.id);
const entity = entities.find((e) => e.id === id);
if (entity) {
Object.assign(entity, req.body);
res.json(entity);
} else {
res.status(404).send('Entity not found');
}
});
app.listen(3000, () => {
console.log('Server listening on port 3000');
});
Client Setup (React with Vite)
Create a new React project using Vite and set up the necessary dependencies.
Initialize the Project
npm create vite@latest warehouse-app --template react
cd warehouse-app
npm install
npm install react-hook-form yup @hookform/resolvers axios react-router-dom
Modify package.json
{
// ... other configurations
"type": "module",
"dependencies": {
// ... dependencies
}
}
Components
src/components/ListPage.jsx
Displays a list of entities with the ability to edit or create new ones.
import React, { useEffect, useState } from 'react';
import axios from 'axios';
import { useNavigate } from 'react-router-dom';
export function ListPage() {
const [entities, setEntities] = useState([]);
const navigate = useNavigate();
useEffect(() => {
axios
.get('http://localhost:3000/api/entities')
.then((response) => setEntities(response.data))
.catch((error) => console.error(error));
}, []);
const handleEdit = (id) => {
navigate(`/edit/${id}`);
};
const handleCreate = () => {
navigate('/create');
};
return (
<div>
<h1>Warehouse Entities</h1>
<button onClick={handleCreate}>Create New Entity</button>
<table>
<thead>
<tr><th>ID</th><th>Name</th><th>Description</th><th>Actions</th></tr>
</thead>
<tbody>
{entities.map((entity) => (
<tr key={entity.id}>
<td>{entity.id}</td>
<td>{entity.name}</td>
<td>{entity.description}</td>
<td>
<button onClick={() => handleEdit(entity.id)}>Edit</button>
</td>
</tr>
))}
</tbody>
</table>
</div>
);
}
src/components/EntityForm.jsx
A reusable form component for creating and editing entities, with validation and dynamic fields.
import React, { useEffect } from 'react';
import { useForm, useFieldArray } from 'react-hook-form';
import { useNavigate } from 'react-router-dom';
import * as yup from 'yup';
import { yupResolver } from '@hookform/resolvers/yup';
import axios from 'axios';
const schema = yup.object().shape({
name: yup.string().required('Name is required').max(50, 'Max 50 characters'),
description: yup.string(),
category: yup.string().required('Category is required'),
status: yup.string(),
radioOption: yup.string(),
controlledField: yup.string().when('radioOption', {
is: 'option1',
then: yup.string().required('This field is required when Option 1 is selected'),
}),
tasks: yup.array().of(
yup.object().shape({
name: yup.string().required('Task name is required'),
status: yup.string().required('Task status is required'),
})
),
});
export function EntityForm({ entityId }) {
const {
register,
control,
handleSubmit,
setValue,
getValues,
formState: { errors },
} = useForm({
resolver: yupResolver(schema),
defaultValues: { tasks: [{ name: '', status: '' }] },
});
const { fields, append, remove } = useFieldArray({ control, name: 'tasks' });
const navigate = useNavigate();
useEffect(() => {
if (entityId) {
axios
.get(`http://localhost:3000/api/entities`)
.then((response) => {
const entity = response.data.find((e) => e.id === parseInt(entityId));
if (entity) {
for (const key in entity) {
setValue(key, entity[key]);
}
}
})
.catch((error) => console.error(error));
}
}, [entityId, setValue]);
const onSubmit = (data) => {
if (entityId) {
const originalValues = getValues();
const changedFields = {};
for (const key in data) {
if (JSON.stringify(data[key]) !== JSON.stringify(originalValues[key])) {
changedFields[key] = data[key];
}
}
axios
.put(`http://localhost:3000/api/entities/${entityId}`, changedFields)
.then(() => navigate('/'))
.catch((error) => console.error(error));
} else {
const filledFields = {};
for (const key in data) {
if (data[key]) {
filledFields[key] = data[key];
}
}
axios
.post('http://localhost:3000/api/entities', filledFields)
.then(() => navigate('/'))
.catch((error) => console.error(error));
}
};
return (
<form
onSubmit={handleSubmit(onSubmit)}
style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '10px' }}
>
<div>
<label>Name*</label>
<input {...register('name')} />
{errors.name && <p style={{ color: 'red' }}>{errors.name.message}</p>}
</div>
<div>
<label>Description</label>
<input {...register('description')} />
</div>
<div>
<label>Category*</label>
<select {...register('category')}>
<option value="">Select Category</option>
<option value="Category A">Category A</option>
<option value="Category B">Category B</option>
</select>
{errors.category && <p style={{ color: 'red' }}>{errors.category.message}</p>}
</div>
<div>
<label>Status</label>
<select {...register('status')}>
<option value="">Select Status</option>
<option value="Available">Available</option>
<option value="Unavailable">Unavailable</option>
</select>
</div>
<div>
<label>Radio Option</label>
<div>
<input type="radio" value="option1" {...register('radioOption')} /> Option 1
<input type="radio" value="option2" {...register('radioOption')} /> Option 2
</div>
</div>
{getValues('radioOption') === 'option1' && (
<>
<div>
<label>Controlled Text*</label>
<input {...register('controlledField')} />
{errors.controlledField && (
<p style={{ color: 'red' }}>{errors.controlledField.message}</p>
)}
</div>
<div>
<label>Controlled Select</label>
<select {...register('controlledSelect')}>
<option value="">Select an option</option>
<option value="Option A">Option A</option>
<option value="Option B">Option B</option>
</select>
</div>
</>
)}
<div style={{ gridColumn: '1 / -1' }}>
<h3>Tasks</h3>
{fields.map((item, index) => (
<div key={item.id} style={{ display: 'flex', gap: '10px' }}>
<div>
<label>Task Name*</label>
<input {...register(`tasks.${index}.name`)} />
{errors.tasks?.[index]?.name && (
<p style={{ color: 'red' }}>{errors.tasks[index].name.message}</p>
)}
</div>
<div>
<label>Task Status*</label>
<select {...register(`tasks.${index}.status`)}>
<option value="">Select Status</option>
<option value="Pending">Pending</option>
<option value="Completed">Completed</option>
</select>
{errors.tasks?.[index]?.status && (
<p style={{ color: 'red' }}>{errors.tasks[index].status.message}</p>
)}
</div>
<button type="button" onClick={() => remove(index)}>
Remove
</button>
</div>
))}
<button type="button" onClick={() => append({ name: '', status: '' })}>
Add Task
</button>
</div>
<div style={{ gridColumn: '1 / -1' }}>
<button type="submit">Submit</button>
</div>
</form>
);
}
src/components/CreatePage.jsx
import React from 'react';
import { EntityForm } from './EntityForm';
export function CreatePage() {
return (
<div>
<h1>Create New Entity</h1>
<EntityForm />
</div>
);
}
src/components/EditPage.jsx
import React from 'react';
import { useParams } from 'react-router-dom';
import { EntityForm } from './EntityForm';
export function EditPage() {
const { id } = useParams();
return (
<div>
<h1>Edit Entity</h1>
<EntityForm entityId={id} />
</div>
);
}
App Setup and Routing
src/App.jsx
import React from 'react';
import { BrowserRouter as Router, Routes, Route } from 'react-router-dom';
import { ListPage } from './components/ListPage';
import { CreatePage } from './components/CreatePage';
import { EditPage } from './components/EditPage';
export function App() {
return (
<Router>
<Routes>
<Route path="/" element={<ListPage />} />
<Route path="/create" element={<CreatePage />} />
<Route path="/edit/:id" element={<EditPage />} />
</Routes>
</Router>
);
}
src/main.jsx
import React from 'react';
import ReactDOM from 'react-dom/client';
import { App } from './App';
ReactDOM.createRoot(document.getElementById('root')).render(
<React.StrictMode>
<App />
</React.StrictMode>
);
CSS Grid Layout Explanation
We use CSS Grid for the form layout because it provides a powerful two-dimensional grid system that allows us to align items both horizontally and vertically:
- Two-Dimensional Control: CSS Grid excels in layouts that require control over both rows and columns, which is essential for complex forms.
- Simplified Layout Management: With CSS Grid, we can create responsive layouts with less code compared to Flexbox when dealing with multiple dimensions.
- Explicit Positioning: It allows precise placement of items within the grid, enhancing the form's structure.
In our form:
form {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 10px;
}
This creates a responsive two-column layout ideal for a multidimensional form.
Running the Application
Start the Server
cd server
npm install
npm start
Start the Client
cd warehouse-app
npm install
npm run dev
Notes
- ES Modules: All imports and exports use ES modules without default exports, as per your requirements.
- Form Validation: Implemented using
yup with required fields, max length validation, and conditional validation based on a radio button.
- Dynamic Fields: Users can add multiple tasks with dynamic form fields utilizing
useFieldArray from react-hook-form.
- Conditional Rendering: Additional inputs controlled by a radio button are conditionally rendered and validated.
- Payload Handling: On form submission, only the fields that the user has filled or changed are sent to the server.
- Inline Error Messages: Validation errors are displayed inline in red below the respective inputs.
This code provides a comprehensive solution fulfilling all the specified requirements. The application is scalable, and the components are reusable, maintaining clean and efficient code.