I am trying to set the defaultValue
for on the <Select />
component from react-select package.
However, when I do set the default value, using a react hook (useState), it does not render the default values.
If I was to hard code the array, it renders he default values fine.
What I have so far
Expectation
I am expecting the select component to render two default values, however nothing has been rendered.
Question
How can I load the default values using react hook useState
?
CodePudding user response:
You can use the value prop to set the selected options, and then keep updating the values from the state. Here is the sample code for the same.
import React, { useEffect, useState } from "react";
import Select from "react-select";
export default function AnimatedMulti() {
const [values, setValues] = useState([]);
const [selectedValues, setSelectedValues] = useState([]);
useEffect(() => {
const data = [
{ value: 1, label: "Label 1" },
{ value: 2, label: "Label 2" },
{ value: 3, label: "Label 3" }
];
setValues(data);
setSelectedValues([data[0]]);
}, []);
const onOptionChange = (options) => {
// Selected options...
console.log("options...", options);
setSelectedValues(options);
};
return (
<Select
closeMenuOnSelect={false}
value={selectedValues}
isMulti
options={values}
onChange={onOptionChange}
/>
);
}
CodePudding user response:
I don't think you can set default value after component have rendered.
Uncontrolled components are components that manage their own state/value. They should not have a value prop (or in other words, value == undefined). If you need to set a value on those, you use the defaultValue prop. But this prop only works on mount / first render of the component. You usually access their state by using a ref, listening to the onChange handler or during form submission (using FormData).
Ref: https://github.com/JedWatson/react-select/issues/4942#issuecomment-987649622
You can try using values attribute to set default values.
import React, { useEffect, useState } from "react";
import Select from "react-select";
export default function AnimatedMulti() {
const [values, setValues] = useState([]);
const [defaultValues, setDefaultValues] = useState(null);
useEffect(() => {
const data = [
{ value: 1, label: "Label 1" },
{ value: 2, label: "Label 2" },
{ value: 3, label: "Label 3" }
];
setValues(data);
setDefaultValues([data[0], data[1]]);
}, []);
return (
<Select
closeMenuOnSelect={false}
value={defaultValues}
isMulti
options={values}
/>
);
}