Search code examples
reactjsselectoncloselistener

Is there a way to find whether the user opened the select field and did not select any option and closed the select field in React


I am working with React.js and using Select component from Material.ui. I want to throw error when a user open the select and close it without selecting any option. I do not want to throw error in the beginning the page render. I tried using onClose in build props.


Solution

  • You can use the state for the selected option:

    const [selectedOption, setSelectedOption] = useState(null);

    Then, on the close event you check if the selectedOption is still null and throw an error. Of course you also need to set the state when the user click an option.