Answer the question
In order to leave comments, you need to log in
How to bind input from react-autosuggest to react-hook-form?
Good evening! I have an input from the react-autosuggest library on the page , which is controlled. I want to add validation and eliminate unnecessary renders using the react-hook-form library . Although the react-hook-form documentation has instructions on how to integrate it into third-party libraries, I can't do it, here's how I do it:
const { handleSubmit, reset, control } = useForm();
<Controller
control={control}
name="some_name"
render={({ onChange, onBlur, value, name }) => (
<SuggestInput
onInputChange={onChange}
inputValue={value}
name={name}
getSuggestions={getSuggestions}
/>
)}
/>
const SuggestInput = ({ onInputChange, inputValue, getSuggestions, name }) => {
const [ options, setOptions ] = useState([]);
const inputProps = {
value: inputValue,
onChange: (event, {newValue}) => onInputChange(newValue)
}
const getSuggestionValue = suggestion => suggestion.name;
const renderSuggestion = suggestion => (
<SuggestWrapper>
{suggestion.name}
</SuggestWrapper>
);
const renderInputComponent = (inputProps) => <input type="text" {...inputProps} name={name} />
const onSuggestionsFetchRequested = ({ value }) => {
getSuggestions(value).then(suggestions => setOptions(suggestions))
};
const onSuggestionsClearRequested = () => setOptions([])
return <Autosuggest
renderInputComponent={renderInputComponent}
suggestions={options}
onSuggestionsFetchRequested={onSuggestionsFetchRequested}
onSuggestionsClearRequested={onSuggestionsClearRequested}
getSuggestionValue={getSuggestionValue}
renderSuggestion={renderSuggestion}
inputProps={inputProps}
theme={theme}
/>
}
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question