I would like to store the value from a select as a boolean and not a string in my Next.js project. Right now the behavior of the select component below is saving it as a string.
export default function Status({ register }) {
return (
<div>
<label htmlFor="Status" className="block text-sm font-medium text-gray-700 dark:text-white">
Status
</label>
<select
id="Status"
name="Status"
{...register("isActive", {})}
>
<option value={true}>Active</option>
<option value={false}>Inactive</option>
</select>
</div>
);
}
How can I store the value as a boolean instead of a string?
CodePudding user response:
there is a workaround to force it to convert to a Boolean, something like this:
<select
{...register("isActive", {
setValueAs: (v) => Boolean(v)
})}
>
<option value={true}>Active</option> //Boolean("any string") gives true
<option value={""}>Inactive</option> //Boolean("") gives false
</select>
setValueAs
returns the input value by running through a function, and since react hook form convert the input value to string
by default, the only way to force it to make it Boolean
is by passing an empty string.
CodePudding user response:
For some reason I can't comment, big brain stackoverflow, ok however.
Erm, since you're storing as a string, I recommend attaching the value to a string, then have a useEffect run with the state as a dependency setting your own personal state that is a boolean. For example
useEffect(() => {setMyState(value === "isActive" ? true : false)}, [value])
I'm having a bit too big of a brain fart, ima just imitate it.
const Component = () => {
// your component, let's say you have these two states
const [linkedState, setLinkedState] = useState("")
const [booleanState, setBooleanState] = useState("")
// this state is linked to the string value, you then make a
useEffect with the state as dependency
useEffect(() => {
// this happens when linkedState changes
setBooleanState(linkedState === "isActive" ? true : false)
// if linkedState equals isActive it sets your boolean to true, else it goes false
}, [linkedState])
}