Your implementation of the form using React Hook Form and Yup is well-structured and aligns with the specified requirements. However, there are a few areas that need adjustment to ensure everything works seamlessly. Below are the key issues identified along with their solutions and an improved version of your code.
Key Issues Identified
-
Inconsistent Naming for Array Fields:
- Problem: In the
CreateItemPage, you're initializing tasks as the array, but in the ItemForm, the array is named endpoints. This mismatch can lead to unexpected behavior.
- Solution: Ensure consistent naming across all components. Decide whether you want to use
tasks or endpoints and stick to it throughout your application.
-
Incorrect Usage of Template Literals in register:
- Problem: The
register function for array fields is using ${index} without backticks, leading to incorrect field registration.
- Solution: Use backticks to correctly interpolate variables within strings.
-
status Field Type:
- Problem: The
status field within the array is currently a text input, but based on your requirements, it should be a select input.
- Solution: Change the
status input to a select with predefined options.
-
Incorrect className Syntax:
- Problem: The
className attributes are using ${} inside {}, which is invalid syntax.
- Solution: Use backticks
` to correctly apply multiple class names.
-
Default Values Alignment:
- Problem: The
CreateItemPage provides default values for tasks, but the form expects endpoints.
- Solution: Update the
defaultValues to use endpoints instead of tasks.
-
Enhanced User Experience:
- Suggestion: Provide placeholders and better labels for clarity. Also, handle scenarios where no endpoints are added gracefully.
Corrected and Improved Code
1. ItemForm Component
// ItemForm.jsx
import { useForm, useFieldArray } from 'react-hook-form';
import { yupResolver } from '@hookform/resolvers/yup';
import * as yup from 'yup';
import { useEffect } from 'react';
import styles from './ItemForm.module.css';
const schema = yup.object({
name: yup.string().required('Name is required').max(50, 'Max length is 50'),
category: yup.string().required('Category is required'),
quantity: yup
.number()
.typeError('Quantity must be a number')
.required('Quantity is required')
.min(1, 'Quantity must be at least 1'),
location: yup.string().notRequired(),
supplier: yup.string().notRequired(),
supplierLocation: yup.string().notRequired(),
showPriceDetails: yup
.string()
.oneOf(['yes', 'no'], 'Please select an option')
.required('Please select an option'),
priceType: yup
.string()
.when('showPriceDetails', {
is: 'yes',
then: (schema) => schema.required('Price Type is required'),
otherwise: (schema) => schema.notRequired(),
}),
price: yup
.number()
.transform((value, originalValue) => (originalValue === '' ? undefined : value))
.when('showPriceDetails', {
is: 'yes',
then: (schema) =>
schema
.required('Price is required')
.typeError('Price must be a number')
.min(1, 'Price must be at least 1'),
otherwise: (schema) => schema.notRequired(),
}),
endpoints: yup.array().of(
yup.object({
endpoint: yup.string().required('Endpoint is required'),
status: yup.string().required('Status is required'),
})
),
});
export const ItemForm = ({ defaultValues, onSubmit }) => {
const {
register,
handleSubmit,
watch,
control,
formState: { errors },
reset,
} = useForm({
defaultValues,
resolver: yupResolver(schema),
});
const { fields, append, remove } = useFieldArray({
control,
name: 'endpoints',
});
const showPriceDetails = watch('showPriceDetails', 'no') === 'yes';
useEffect(() => {
reset(defaultValues);
}, [defaultValues, reset]);
// Custom submit handler that logs affected fields
const handleFormSubmit = (data) => {
console.log('Submitted data:', data);
// Log specific fields you want to track
console.log('Name:', data.name);
console.log('Category:', data.category);
console.log('Quantity:', data.quantity);
console.log('Supplier:', data.supplier);
console.log('Show Price Details:', data.showPriceDetails);
if (data.showPriceDetails === 'yes') {
console.log('Price Type:', data.priceType);
console.log('Price:', data.price);
}
console.log('Endpoints:', data.endpoints);
onSubmit(data); // Call the original onSubmit prop
};
return (
<div className="form-container">
<form onSubmit={handleSubmit(handleFormSubmit)} className="form-wrapper">
<div className={`${styles.formGrid} ${styles.grid3}`}>
<div className={styles.formGroup}>
<label htmlFor="name">Name*:</label>
<input
id="name"
{...register('name')}
className={errors.name ? styles.inputError : ''}
placeholder="Enter item name"
/>
{errors.name && <p className={styles.errorMessage}>{errors.name.message}</p>}
</div>
<div className={styles.formGroup}>
<label htmlFor="category">Category*:</label>
<select
id="category"
{...register('category')}
className={errors.category ? styles.inputError : ''}
>
<option value="">Select category</option>
<option value="Electronics">Electronics</option>
<option value="Furniture">Furniture</option>
<option value="Clothing">Clothing</option>
<option value="Food">Food</option>
<option value="Toys">Toys</option>
<option value="Books">Books</option>
<option value="Sports">Sports</option>
</select>
{errors.category && (
<p className={styles.errorMessage}>{errors.category.message}</p>
)}
</div>
<div className={styles.formGroup}>
<label htmlFor="quantity">Quantity*:</label>
<input
type="number"
id="quantity"
{...register('quantity')}
className={errors.quantity ? styles.inputError : ''}
placeholder="Enter quantity"
/>
{errors.quantity && (
<p className={styles.errorMessage}>{errors.quantity.message}</p>
)}
</div>
</div>
<div className={`${styles.formGrid} ${styles.grid2}`}>
<div className={styles.formGroup}>
<label htmlFor="supplier">Supplier:</label>
<input
id="supplier"
{...register('supplier')}
className={errors.supplier ? styles.inputError : ''}
placeholder="Enter supplier name"
/>
{errors.supplier && (
<p className={styles.errorMessage}>{errors.supplier.message}</p>
)}
</div>
<div className={styles.formGroup}>
<label htmlFor="supplierLocation">Supplier Location:</label>
<input
id="supplierLocation"
{...register('supplierLocation')}
className={errors.supplierLocation ? styles.inputError : ''}
placeholder="Enter supplier location"
/>
{errors.supplierLocation && (
<p className={styles.errorMessage}>{errors.supplierLocation.message}</p>
)}
</div>
</div>
<div className={styles.formGroup}>
<label>Show Price Details?</label>
<div className={styles.radioGroup}>
<label>
<input
type="radio"
value="yes"
{...register('showPriceDetails')}
defaultChecked={defaultValues?.showPriceDetails === 'yes'}
/>
Yes
</label>
<label>
<input
type="radio"
value="no"
{...register('showPriceDetails')}
defaultChecked={defaultValues?.showPriceDetails !== 'yes'}
/>
No
</label>
</div>
{errors.showPriceDetails && (
<p className={styles.errorMessage}>{errors.showPriceDetails.message}</p>
)}
</div>
{showPriceDetails && (
<div className={`${styles.formGrid} ${styles.grid2}`}>
<div className={styles.formGroup}>
<label htmlFor="priceType">Type:</label>
<select
id="priceType"
{...register('priceType')}
className={errors.priceType ? styles.inputError : ''}
>
<option value="">Select type</option>
<option value="For Sale">For Sale</option>
<option value="For Buying">For Buying</option>
</select>
{errors.priceType && (
<p className={styles.errorMessage}>{errors.priceType.message}</p>
)}
</div>
<div className={styles.formGroup}>
<label htmlFor="price">Price:</label>
<input
type="number"
id="price"
{...register('price')}
className={errors.price ? styles.inputError : ''}
placeholder="Enter price"
/>
{errors.price && (
<p className={styles.errorMessage}>{errors.price.message}</p>
)}
</div>
</div>
)}
<div className={`${styles.formGroup} ${styles.fullWidth}`}>
<h3>Endpoints</h3>
{fields.length === 0 && <p>No endpoints added.</p>}
{fields.map((endpoint, index) => (
<div key={endpoint.id} className={`${styles.formGrid} ${styles.grid2}`}>
<div className={styles.formGroup}>
<label htmlFor={`endpoints.${index}.endpoint`}>Endpoint {index + 1}*:</label>
<input
id={`endpoints.${index}.endpoint`}
{...register(`endpoints.${index}.endpoint`)}
className={
errors.endpoints?.[index]?.endpoint ? styles.inputError : ''
}
placeholder="Enter endpoint URL"
/>
{errors.endpoints?.[index]?.endpoint && (
<p className={styles.errorMessage}>
{errors.endpoints[index].endpoint.message}
</p>
)}
</div>
<div className={styles.formGroup}>
<label htmlFor={`endpoints.${index}.status`}>Status*:</label>
<select
id={`endpoints.${index}.status`}
{...register(`endpoints.${index}.status`)}
className={
errors.endpoints?.[index]?.status ? styles.inputError : ''
}
>
<option value="">Select status</option>
<option value="Active">Active</option>
<option value="Inactive">Inactive</option>
<option value="Pending">Pending</option>
</select>
{errors.endpoints?.[index]?.status && (
<p className={styles.errorMessage}>
{errors.endpoints[index].status.message}
</p>
)}
</div>
<div className={styles.formGroup}>
<button
type="button"
className={styles.removeEndpointButton}
onClick={() => remove(index)}
>
Remove Endpoint
</button>
</div>
</div>
))}
<button
type="button"
className={styles.addEndpointButton}
onClick={() => append({ endpoint: '', status: '' })}
>
Add Endpoint
</button>
</div>
<button type="submit" className={styles.actionButton}>
Submit
</button>
</form>
</div>
);
};
2. EditItemPage Component
// EditItemPage.jsx
import { useEffect, useState } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import { getItems, updateItem } from '../../api';
import { ItemForm } from '../../components/ItemForm/ItemForm';
import styles from './EditItemPage.module.css';
export const EditItemPage = () => {
const { id } = useParams();
const navigate = useNavigate();
const [item, setItem] = useState(null);
useEffect(() => {
getItems().then((response) => {
const foundItem = response.data.find((item) => item.id === parseInt(id));
setItem(foundItem);
});
}, [id]);
const handleSubmit = (data) => {
updateItem(id, data).then(() => navigate('/'));
};
if (!item) {
return <p>Loading...</p>;
}
return (
<div className={styles.formContainer}>
<div className={styles.formWrapper}>
<h1 className={styles.h1}>Edit Item</h1>
<ItemForm onSubmit={handleSubmit} defaultValues={item} />
<button onClick={() => navigate('/')} className={styles.actionButton}>
Back to List
</button>
</div>
</div>
);
};
3. CreateItemPage Component
// CreateItemPage.jsx
import { useNavigate } from 'react-router-dom';
import { createItem } from '../../api';
import { ItemForm } from '../../components/ItemForm/ItemForm';
import styles from './CreateItemPage.module.css';
export const CreateItemPage = () => {
const navigate = useNavigate();
const handleSubmit = (data) => {
createItem(data).then(() => navigate('/'));
};
return (
<div className={styles.formContainer}>
<h1 className={styles.h1}>Create Item</h1>
<ItemForm
onSubmit={handleSubmit}
defaultValues={{
name: '',
category: '',
quantity: 1,
location: '',
supplier: '',
supplierLocation: '',
showPriceDetails: 'no',
endpoints: []
}}
/>
<button className={styles.backButton} onClick={() => navigate('/')}>
Back to List
</button>
</div>
);
};
Detailed Explanations
-
Consistent Naming:
- Changed all references from
tasks to endpoints to maintain consistency across ItemForm, EditItemPage, and CreateItemPage.
-
Correct Registration of Array Fields:
- Wrapped the
register paths in backticks to correctly interpolate the index.
{...register(`endpoints.${index}.endpoint`)}
{...register(`endpoints.${index}.status`)}
-
Changing status to a Select Input:
- Updated the
status field within the endpoints array to be a select input with predefined options like "Active", "Inactive", and "Pending".
- This provides better control over the possible values and enhances user experience.
-
Fixing className Syntax:
- Used backticks to combine multiple class names correctly.
className={`${styles.formGrid} ${styles.grid3}`}
-
Updating defaultValues in CreateItemPage:
- Provided empty strings for optional fields and an empty array for
endpoints to align with the form's expectations.
defaultValues={{
name: '',
category: '',
quantity: 1,
location: '',
supplier: '',
supplierLocation: '',
showPriceDetails: 'no',
endpoints: [],
}}
-
Enhanced User Experience:
- Added placeholders to input fields to guide users.
- Displayed a message when no endpoints are added to inform users.
-
Loading State in EditItemPage:
- Added a loading state to handle scenarios where the item data is being fetched.
if (!item) {
return <p>Loading...</p>;
}
-
Accessibility Enhancements:
- Added
htmlFor and id attributes to labels and inputs to improve accessibility.
Conclusion
By addressing the inconsistencies and improving the code structure, the form now fully adheres to the specified requirements:
- At least 2 select inputs and 4 text inputs: Achieved with
category, priceType, status (selects) and name, supplier, supplierLocation, endpoint (text inputs).
- Optional fields:
location, supplier, and supplierLocation are optional.
- Radio button controlling additional inputs: The
showPriceDetails radio controls the display of priceType and price.
- Array inputs: Users can add multiple
endpoints, each with a name (endpoint) and status (select).
Ensure that your CSS modules (ItemForm.module.css, EditItemPage.module.css, and CreateItemPage.module.css) are correctly defined to style the form as intended.
Feel free to reach out if you have further questions or need additional assistance!