简体   繁体   中英

How do I set a value for a <select> with React without using onChange?

I got the following HTML select element

<select id="bars" onChange={(e) => onBarChange(e)}>
  {props.results.map((bar, y) => (
    <option value={bar.id} key={bar.id} data-key={bar.id}>
      {bar.name} in {bar.city}
    </option>
  ))}
</select>;

with the following onChange method as a callback:

const onBarChange = (e: React.ChangeEvent<HTMLSelectElement>) => {
  setBarId(parseInt(e.target.value));
};

However, whenever theres only one bar in props.results (props.results.length === 1) then onBarChange(e) will never be called and thus barId will always remain 0 (default select value I guess).

I tried to put that logic into the submit form like following:

if(props.results.length === 1) {
  setBarId(props.results[0].id)
}

but that isn't working either. If I console log props.results[0].id I get the correct id but if I console log barId right after this its still 0 again. How can that happen? Is a rerender triggered and the select immediately sets the default 0 as the state again?

How can I resolve this so the submit button wrapping this select is sending the correct barId to the backend whenver theres just one bar in props.results (should of course also work with multiple bars..)?

When you are creating barId using useState pass default value.

const [barId, setBarId] = useState(props?.results[0]?.id ?? 0)


const onBarChange = (e: React.ChangeEvent<HTMLSelectElement>) => {
    setBarId(parseInt(e.target.value));
};


<select id="bars" onChange={(e) => onBarChange(e)}>
    {props.results.map((bar, y) => (
        <option value={bar.id} key={bar.id} data-key={bar.id}>
            {bar.name} in {bar.city}
        </option>
    ))}
</select>;

Another thing you can do is add an empty value first.

<select id="bars" onChange={(e) => onBarChange(e)}>
    <option>Select Bar</option>
    {props.results.map((bar, y) => (
        <option value={bar.id} key={bar.id} data-key={bar.id}>
            {bar.name} in {bar.city}
        </option>
    ))}
</select>;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM