Revert dropdown to default option after Submit

Viewed 137

I have a dropdown with a couple of fields that are used for updating an entry in the db. However I have an issue when I click submit to have a dropdown go back to initial - default state.

Here is the dropdown


<select className="select--field" name="products" onChange={(e) => {handleChange(e)}}>
    <option value={null}>Please select a product</option>
    {data.products.map(({id, productName}) => (
         <option key={id} value={id}>{productName}</option>
     ))}
</select> 

What handleChange does is setting up selected product id as currently selected product so I can map through data and set placeholders as pre-filled data in fields below (not shown here).

I get the data via GraphQL useQuery, it might be that I am not controlling this field as I should so I can't really control it after an event like onSubmit. All suggestions are welcome, thnx.

1 Answers

You can use useRef. It is an effective tool to control your form elements.

Here is an example (https://codesandbox.io/s/billowing-haze-zmq4t?file=/src/App.js):

const products = [
  {id: 112, productName: "Prod 1"},
  {id: 113, productName: "Prod 2"},
]

export default function App() {
  const dropdown = useRef();

const handleChange = () => {
  console.log('do stuff...')
  setTimeout(() => {dropdown.current.value = ""}, 2000) // <- simulating some process...
  
}

  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>

      <select ref={dropdown} className="select--field" name="products" onChange={(e) => {handleChange(e)}}>
        <option value={""}>Please select a product</option>
        {products.map(({id, productName}) => (
            <option key={id} value={id}>{productName}</option>
        ))}
    </select> 
    </div>
  );
}
Related