G
G
Gimir2020-10-22 18:36:42
React
Gimir, 2020-10-22 18:36:42

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}
       />
     )}
/>


Here is the SuggestInput component :
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}
        />
}


I get this error when the component is rendered:
Uncaught TypeError: Cannot read property 'trim' of undefined in SuggestInput component

How do I link these two so that everything works as it should?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question