Home > Software design >  How can I setState to the default selected option's value for HTML <select>
How can I setState to the default selected option's value for HTML <select>

Time:12-31

I'm trying to figure out how I can set the initial state to the default selected option's value. Since each {hit} will have different available_weights, I can't simply put useState(hit.price_gram).

  "hit": {
      ...
      "available_weights": "[\"half gram\", \"gram\"]",
      "price_gram": "44.0",
      "price_half_gram": "22.0",
      "price_ounce": null,
      ...
    }


function Price({ hit }) {
    
      const [price, setPrice] = useState() // Need to set this as the value of the default selected option within the .map()
      const handleChange = (e) => setPrice(e.target.value)
    
      return (
        <>
          <span>{price}</span>
    
          <select onChange={handleChange}>
            {hit.available_weights.map((weight, index) => {
              const weight_price = Object.keys(hit).filter(key => key === "price_"   weight.split(' ').join('_'))
              return (
                <option key={weight} value={hit[weight_price]} selected={index === 0}>
                  {weight}
                </option>
              )
            })}
          </select>
        </>
      )
    }

CodePudding user response:

You can do it like that

function Price({ hit }) {
  const weights = hit.available_weights.map((weight, index) => {
    const weight_price = Object.keys(hit).filter(
      (key) => key === "price_"   weight.split(" ").join("_")
    );
    return {
      weight,
      weight_price,
      index,
    };
  });
  const [price, setPrice] = useState(hit[weights[0].weight_price]);
  const handleChange = (e) => setPrice(e.target.value);

  return (
    <>
      <span>{price}</span>

      <select onChange={handleChange}>
        {weights.map(({ weight, weight_price, index }) => {
          return (
            <option
              key={weight}
              value={hit[weight_price]}
              selected={index === 0}
            >
              {weight}
            </option>
          );
        })}
      </select>
    </>
  );
}

  • Related