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);
- not "value" property used. change to "defaultValue" attribute
- 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.