I'm using react hook form and I want to be set dynamically one text input box based on one radio button selected condition. I have radio buttons that track the delivery methods are home, office and others. if the user clicks other I want to show an input box and want to hide the radio buttons. I hope that makes sense. I tried a lot of ways it doesn't work. Any idea will helpful I not working properly
{(watch('tag') == 'others') ? <Input
{...register('otherField')}
label="Others"
variant="outline"
className="col-span-2 w-full"
/>:
<div className="flex items-center space-x-4 rtl:space-x-reverse">
<Radio
id="home"
{...register('tag')}
type="radio"
value={'home'}
label="Home"
name={'tag'}
/>
<Radio
id="work"
{...register('tag')}
type="radio"
value={'Work'}
label="Work"
name={'tag'}
/>
<Radio
id="others"
{...register('tag')}
type="radio"
value={'others'}
label="Others"
name={'tag'}
/>
</div>
}
Radio Button Component
import React, { InputHTMLAttributes } from 'react';
import styles from './radio.module.css';
export interface Props extends InputHTMLAttributes<HTMLInputElement> {
className?: string;
label?: string;
name: string;
id: string;
error?: string;
}
const Radio = React.forwardRef<HTMLInputElement, Props>(
({ className, label, name, id, error, ...rest }, ref) => {
return (
<div className={className}>
<div className="flex items-center">
<input
id={id}
name={name}
type="radio"
ref={ref}
className={styles.radio_input}
{...rest}
/>
<label htmlFor={id} className="text-body text-sm">
{label}
</label>
</div>
{error && (
<p className="my-2 text-xs ltr:text-right rtl:text-left text-red-500">
{error}
</p>
)}
</div>
);
}
);
export default Radio;
CodePudding user response:
hello i just replicated your code this sandbox and it's working fine: codesandbox
App.js
import "./styles.css";
import { useForm } from "react-hook-form";
import Radio from "./Radio";
export default function App() {
const { register, handleSubmit, watch } = useForm();
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
{watch("tag") === "others" ? (
<input
{...register("otherField")}
variant="outline"
className="col-span-2 w-full"
/>
) : (
<div className="flex items-center space-x-4 rtl:space-x-reverse">
<form>
<Radio
id="home"
{...register("tag")}
type="radio"
value={"home"}
label="Home"
name={"tag"}
/>
<Radio
id="work"
{...register("tag")}
type="radio"
value={"Work"}
label="Work"
name={"tag"}
/>
<Radio
id="others"
{...register("tag")}
type="radio"
value={"others"}
label="Others"
name={"tag"}
/>
<button onClick={handleSubmit((val) => console.log(val))}>
click
</button>
</form>
</div>
)}
</div>
);
}