How to set selected value of a select drop down to null with React?

Sometimes, we want to set selected value of a select drop down to null with React.

In this article, we’ll look at how to set selected value of a select drop down to null with React.

How to set selected value of a select drop down to null with React?

To set selected value of a select drop down to null with React, we can set the state we use as the value of the value prop of the select drop down to null.

For instance, we write:

import React, { useState } from "react";

export default function App() {
  const [selected, setSelected] = useState(null);

  return (
    <div>
      <select
        onChange={(e) => setSelected(e.target.value || null)}
        value={selected || ""}
      >
        <option value=""></option>
        <option value="1">cook dinner</option>
        <option value="2">do dishes</option>
        <option value="3">walk dog</option>
      </select>
    </div>
  );
}

to set onChange to a function that calls setSelected to e.target.value which is the selected value if it’s truthy.

Otherwise, we set it to null.

Next, we set the value prop to selected if it’s truthy and an empty string otherwise.

Since null is falsy, value will be an empty string if selected is null, which matches the value attribute of the first choice.

As a result, when we select the first choice, the empty option will be displayed.

Conclusion

To set selected value of a select drop down to null with React, we can set the state we use as the value of the value prop of the select drop down to null.