I have a component that renders a reusable dropdown list. When I use it to add a new project, I can set category. But, when I use it to edit the project, the dropdown doesn't show the selected category. However I have sent the category _id as props.
export default function RHFSelect({
label,
name,
register,
options,
required,
validationschema,
errors,
categoryID = "",
}) {
return (
<div>
<select
className="textField__input"
{...register(name, validationschema)}
id={name}
defaultValue={categoryID}
>
<option value="">Please select the project category</option>
{options.map((option) => {
return (
<option key={option.value} value={option.value}>
{option.label}
</option>
);
})}
</select>
{errors && errors[name] && (
<span className="text-error block text-sm mt-2">
{errors[name]?.message}
</span>
)}
</div>
);
}
The options is list of categories fetch from DB. The categoryID is an empty string by default but in edit project mode, it is an id of a category, the project belongs to it. I expect that in add mode it shows "Please select project category" and in edit mode it shows the category that I selected before.
Additional note: Unfortunately, I forgot to add a hint and the hint is I have problem in initial render after that the dropdown shows selected category correctly.
Thanks in advanced.
Don't use default value directly in select instead use in react-hook-form or any library form you are using or update like this for a simple solution
<select
className="textField__input"
{...register(name, validationschema)}
id={name}
value={categoryID}
onChange={(e) => register(name).onChange(e)}>
or use
setValue('notRegisteredInput', 'value'); // example in useEffect
hook to set the initial value in re-render.