Конечно! Вот обновленный код ItemForm и ItemTable, которые соответствуют вашим требованиям:
Обновленный ItemForm:
import { useForm, useFieldArray } from 'react-hook-form';
import { yupResolver } from '@hookform/resolvers/yup';
import * as yup from 'yup';
import { useEffect } from 'react';
// Схема валидации
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().required('Quantity is required').min(1),
location: yup.string().optional(),
supplier: yup.string().optional(),
supplierLocation: yup.string().optional(),
showPriceDetails: yup.string().required('Please select an option'),
priceType: yup.string().when('showPriceDetails', {
is: 'yes',
then: yup.string().required('Price Type is required'),
otherwise: yup.string().notRequired(),
}),
price: yup.number().when('showPriceDetails', {
is: 'yes',
then: yup.number().required('Price is required').min(0),
otherwise: yup.number().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]);
return (
<form onSubmit={handleSubmit(onSubmit)} className="form-grid">
{/* Основная информация */}
<div className="grid">
<label>Name:</label>
<input {...register('name')} />
{errors.name && <p>{errors.name.message}</p>}
<label>Category:</label>
<select {...register('category')}>
<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>{errors.category.message}</p>}
<label>Quantity:</label>
<input type="number" {...register('quantity')} />
{errors.quantity && <p>{errors.quantity.message}</p>}
<label>Location:</label>
<input {...register('location')} />
</div>
{/* Опциональные поля */}
<div className="grid">
<label>Supplier (Optional):</label>
<input {...register('supplier')} />
<label>Supplier Location (Optional):</label>
<input {...register('supplierLocation')} />
</div>
{/* Радио-кнопки для управления дополнительными полями */}
<div>
<label>Show Price Details?</label>
<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>
{errors.showPriceDetails && <p>{errors.showPriceDetails.message}</p>}
</div>
{showPriceDetails && (
<div className="grid">
<label>Type:</label>
<select {...register('priceType')}>
<option value="">Select type</option>
<option value="For Sale">For Sale</option>
<option value="For Buying">For Buying</option>
</select>
{errors.priceType && <p>{errors.priceType.message}</p>}
<label>Price:</label>
<input type="number" {...register('price')} placeholder="Enter price" />
{errors.price && <p>{errors.price.message}</p>}
</div>
)}
{/* Endpoints */}
<div>
<h3>Endpoints</h3>
{fields.map((endpoint, index) => (
<div key={endpoint.id} className="grid">
<label>Endpoint {index + 1}:</label>
<input
{...register(`endpoints.${index}.endpoint`)}
placeholder={`Endpoint ${index + 1}`}
/>
{errors.endpoints?.[index]?.endpoint && (
<p>{errors.endpoints[index].endpoint.message}</p>
)}
<label>Status:</label>
<select {...register(`endpoints.${index}.status`)}>
<option value="">Select status</option>
<option value="Delivering">Delivering</option>
<option value="Delivered">Delivered</option>
<option value="Pending">Pending</option>
<option value="Delayed">Delayed</option>
<option value="Canceled">Canceled</option>
</select>
{errors.endpoints?.[index]?.status && (
<p>{errors.endpoints[index].status.message}</p>
)}
<button type="button" onClick={() => remove(index)}>
Remove Endpoint
</button>
</div>
))}
<button
type="button"
onClick={() => append({ endpoint: '', status: '' })}
>
Add Endpoint
</button>
</div>
{/* Кнопка отправки */}
<button type="submit">Save</button>
</form>
);
};
Что было изменено в ItemForm:
- Радио-кнопки изменены на "Yes" и "No":
<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>
- Добавлено поле выбора и текстовое поле для цены, отображаемые при выборе "Yes":
{showPriceDetails && (
<div className="grid">
<label>Type:</label>
<select {...register('priceType')}>
<option value="">Select type</option>
<option value="For Sale">For Sale</option>
<option value="For Buying">For Buying</option>
</select>
{errors.priceType && <p>{errors.priceType.message}</p>}
<label>Price:</label>
<input type="number" {...register('price')} placeholder="Enter price" />
{errors.price && <p>{errors.price.message}</p>}
</div>
)}
- Обновлена схема валидации с использованием условной валидации для
priceType и price:
showPriceDetails: yup.string().required('Please select an option'),
priceType: yup.string().when('showPriceDetails', {
is: 'yes',
then: yup.string().required('Price Type is required'),
otherwise: yup.string().notRequired(),
}),
price: yup.number().when('showPriceDetails', {
is: 'yes',
then: yup.number().required('Price is required').min(0),
otherwise: yup.number().notRequired(),
}),
- Использован
watch из react-hook-form для отслеживания значения showPriceDetails:
const showPriceDetails = watch('showPriceDetails', 'no') === 'yes';
Обновленный ItemTable:
import { Link } from 'react-router-dom';
export const ItemTable = ({ items = [] }) => {
return (
<table>
<thead>
<tr>
<th>Name</th>
<th>Category</th>
<th>Quantity</th>
<th>Location</th>
<th>Supplier</th>
<th>Supplier Location</th>
<th>Price Type</th>
<th>Price</th>
<th>Endpoints</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
{items.length > 0 ? (
items.map((item) => (
<tr key={item.id}>
<td>{item.name}</td>
<td>{item.category}</td>
<td>{item.quantity}</td>
<td>{item.location}</td>
<td>{item.supplier || 'N/A'}</td>
<td>{item.supplierLocation || 'N/A'}</td>
<td>{item.showPriceDetails === 'yes' ? item.priceType : 'N/A'}</td>
<td>
{item.showPriceDetails === 'yes' && typeof item.price !== 'undefined'
? item.price
: 'N/A'}
</td>
<td>
{item.endpoints && item.endpoints.length > 0 ? (
<ul>
{item.endpoints.map((endpoint, index) => (
<li key={index}>{`${endpoint.endpoint} - ${endpoint.status}`}</li>
))}
</ul>
) : (
<p>No endpoints available</p>
)}
</td>
<td>
<Link to={`/edit/${item.id}`}>Edit</Link>
</td>
</tr>
))
) : (
<tr>
<td colSpan="10">No items available</td>
</tr>
)}
</tbody>
</table>
);
};
Что было изменено в ItemTable:
- Добавлены новые столбцы "Price Type" и "Price" в заголовок таблицы:
<tr>
<th>Name</th>
<th>Category</th>
<th>Quantity</th>
<th>Location</th>
<th>Supplier</th>
<th>Supplier Location</th>
<th>Price Type</th>
<th>Price</th>
<th>Endpoints</th>
<th>Actions</th>
</tr>
- Отображение значений "Price Type" и "Price" только если
showPriceDetails равно "yes":
<td>{item.showPriceDetails === 'yes' ? item.priceType : 'N/A'}</td>
<td>
{item.showPriceDetails === 'yes' && typeof item.price !== 'undefined'
? item.price
: 'N/A'}
</td>
- Обновлен
colSpan в случае отсутствия элементов (теперь colSpan="10"):
<tr>
<td colSpan="10">No items available</td>
</tr>
Примечания:
-
Управление состоянием showPriceDetails: Вместо использования useState, мы используем watch из react-hook-form для отслеживания значения showPriceDetails. Это позволяет нам динамически отображать или скрывать поля без дополнительного состояния.
-
Схема валидации: С помощью метода when из yup мы устанавливаем условную валидацию для полей priceType и price. Они становятся обязательными, только если showPriceDetails равно "yes".
-
Отображение в таблице: В компоненте ItemTable мы проверяем значение showPriceDetails для каждого элемента и отображаем priceType и price, только если это значение равно "yes". В противном случае отображается "N/A".
-
Обработка опциональных полей: Если какое-либо опциональное поле отсутствует (например, supplier или supplierLocation), мы отображаем "N/A" для ясности.
Теперь ваша форма будет отображать радиокнопки "Yes" и "No" для поля "Show Price Details". Если пользователь выбирает "Yes", появляются дополнительные поля для выбора типа ("For Sale" или "For Buying") и ввода цены. Эти данные будут корректно отображаться в таблице, только если пользователь выбрал "Yes".
Если у вас есть дополнительные вопросы или нужна помощь с дальнейшими изменениями, пожалуйста, сообщите мне!