How to clear the input value on blur? #855
-
I want to clear the input text if nothing selected when a user focus out from the component. There is a prop called onInputChange but I couldn't find how to make the input value controllable. I don't want to use ref and assign events for this. |
Beta Was this translation helpful? Give feedback.
Answered by
ericgio
Jun 17, 2024
Replies: 1 comment
-
Using a ref is the right way to achieve this behavior. Use const Example = () => {
const typeaheadRef = useRef(null);
const [selected, setSelected] = useState([]);
return (
<Typeahead
id="clear-on-blur"
onBlur={() => {
if (!selected.length) {
typeaheadRef.current.clear();
}
}}
onChange={setSelected}
options={options}
ref={typeaheadRef}
selected={selected}
/>
);
}; |
Beta Was this translation helpful? Give feedback.
0 replies
Answer selected by
ericgio
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Using a ref is the right way to achieve this behavior. Use
onBlur
to check whether there are any selections, and clear the component if not:Working sandbox