Store an object value instead of a string one #1818
-
Hi ! I'm developping a location input with a complex return value which can be: {
streetNumber: 0,
address: "Rue de la Mairie",
postalCode: "11000",
city: "Carcassonne",
country: "France"
} or simply {
lat: 1.012346,
long: -1.84981,
city: "LONDON",
country: "UK"
} The object structure can change according to the place type and is definitely more complex than a simple string. I'd like to get the object in the handleSubmit callback. What is the clean way to do that using react-hook-form ? I'm currently creating hidden inputs and registering them, but it seems hacky and I'm sure there is a better way. |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 1 reply
-
input type hidden is actually the correct and HTML standard for hidden values. however, you can build a custom component and wrapped with Controller. personally i prefer to stick with HTML standard. |
Beta Was this translation helpful? Give feedback.
-
For reference, here is what I finally did: I wrapped every input in a Controller. Sometimes the value is a string, sometimes it's something else. Anyway, that means if I want to use an input with react-hook-forms, I always pass the component a Here is an example with my LocationInput component (it may be what you want inside: a map, a dropdown... React hook form only handles the validation and the object value) type InputLocationProps = {
value: {lat: number, long: number;},
onChange: ({lat: number, long: number}) => void
}
const InputLocation: ReactFC<InputLocationProps> = props => (
<SomeMapComponent selectedLocation={{lat: propx.value.lat, long: props.value.long}} onSelectLocation{(lat, long}=>props.onChange({lat, long}) />
);
const ControlledInputLocation: React.FC<ControlledInputProps<
InputLocationProps
>> = ({ control, rules, name, ...props }) => (
<Controller
as={<InputLocation {...props} />}
control={control}
rules={rules}
name={name}
/>
); Take a look to the doc of Controller and use |
Beta Was this translation helpful? Give feedback.
For reference, here is what I finally did: I wrapped every input in a Controller. Sometimes the value is a string, sometimes it's something else.
Anyway, that means if I want to use an input with react-hook-forms, I always pass the component a
control
property, aname
property and arules
property.Here is an example with my LocationInput component (it may be what you want inside: a map, a dropdown... React hook form only handles the validation and the object value)