0

I want the select box to have a value set by default.The select box generated at this time is dynamically generated with the fetch data. Default values are also fetch from the API result. But it doesn't work from time to time. In some cases, the default is selected, but in others, the default is not selected. So I knew from search "key" attribute use it. So I used it.

import React, { useEffect, useState } from "react";
import axios from "axios";

function SelectBox({ value, name }, ref) {
  const [data, setData] = useState([]);
  useEffect(() => {
    const fetchData = async () => {
      try {
        const result = await axios.post(
          `/api/...`
        );
        setData(result.data);
      } catch (e) {
        console.error(e);
      }
    };
    fetchData();
  }, []);

  return (
    <select key={value} name={name} defaultValue={value} ref={ref}>
      {data.map((item, index) => (
        <option key={index} value={item.id}>
          {item.value}
        </option>
      ))}
    </select>
  );
}

export default React.forwardRef(SelectBox);
  1. not "value" property used. change to "defaultValue" attribute
  2. add "key" attribute, and "key" props value is I want to display default value

But it still doesn't work. There is no problem with the data generated in the API and select box.
I would appreciate it if you could let me know which part was wrong. Here's an example that makes it almost like a problem situation. https://codesandbox.io/s/sad-violet-mcg9u?file=/src/App.js
I would appreciate your help.

cozy60
  • 27
  • 7

2 Answers2

1

You only need to set value in your select and it should work:

<select key={value} name={name} value={value} ref={ref}>

An alternative is to use the selected attribute in your option:

{data.map((item, index) => (
  <option key={index} value={item.id} selected={item.id === value}>
    {item.value}
  </option>
))}

I tested both options on your CodeSandbox and they both work: https://codesandbox.io/s/wonderful-knuth-rpnmk?file=/src/App.js

More info: How can I set the default value for an HTML <select> element?

Bruno Monteiro
  • 4,153
  • 5
  • 29
  • 48
0

maybe u should render select box after fetch data

check ur data is not empty array and render select box

    data.length !== 0 && <select key={value} name={name} defaultValue={value} ref={ref}>
      {data.map((item, index) => (
        <option key={index} value={item.id}>
          {item.value}
        </option>
      ))}
    </select>