0

I've been looking at form elements in React and having checked the documentation (https://reactjs.org/docs/forms.html#the-select-tag) and answers on stackoverflow such as (How to set a default value in react-select and React JSX: selecting "selected" on selected <select> option).

I'm not creating a select component as such. I have a header component, and when I render the header, I have a select element in it. The select element is populated via an Ajax call and this might be why the default value is not being set.

My code looks like this:

useEffect(() => {
  // do ajax call and set currenclyList
});
return (
  <header className="row block plain center">
    <div>
      <h1>Shopping Cart</h1>
    </div>
    <div>
      <select
        className="dropdown"
        onChange={handleChange}
        defaultValue="USDGBP"
      >
        {Object.keys(currencyList).map((element) => {
          return (
            <option
              key={element}
              value={element}
              data-price={currencyList[element]}
            >
              {element}
            </option>
          );
        })}
      </select>
    </div>
  </header>
);

I have set the defaultValue="USDGBP", as I know that the dropdown list does get populated with that and several others eventually. But when the element is rendered, it is always set to the first item in the list.

How can I force this select element to find the USDGBP element and set that as the default value?

Janez Kuhar
  • 3,705
  • 4
  • 22
  • 45
Husman
  • 6,819
  • 9
  • 29
  • 47
  • @DaviMendesDev From the first link in the OP's question: *"React, instead of using this `selected` attribute, uses a `value` attribute on the root select tag."* – Janez Kuhar Apr 17 '21 at 15:07

1 Answers1

2

Use value prop instead of defaultValue.

function App() {
  const currencyList = { GBPUSD: 16.45, USDGBP: 15.74, EURGBP: 12.45 };
  const [selected, setSelected] = React.useState("USDGBP");

  const handleChange = (event) => {
    setSelected(event.target.value);
  };
  return (
    <header className="row block plain center">
      <div>
        <h1>Shopping Cart</h1>
      </div>
      <div>
        <select className="dropdown" onChange={handleChange} value={selected}>
          {Object.keys(currencyList).map((element) => {
            return (
              <option
                value={element}
                key={element}
                data-price={currencyList[element]}
              >
                {element}
              </option>
            );
          })}
        </select>
      </div>
    </header>
  );
}

ReactDOM.render(<App />, document.getElementById("root"));
<div id="root"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.production.min.js"></script>
Janez Kuhar
  • 3,705
  • 4
  • 22
  • 45
Kevin Koech
  • 78
  • 1
  • 3