0
votes

I'm trying to set the default value for my react-select, but it is not working properly.

import Select from 'react-select';

I have the state for the selected properties

const [ selectedProps, setSelectedProps ] = useState([]);

In my useEffect, I set the value coming from the props

setSelectedProps(props.location.user.properties);

Right before rendering the component, I log the data to make sure that is correct

console.log(properties);
console.log(selectedProps);

Here is my select

<Select
    defaultValue={selectedProps}
    isMulti
    name="properties"
    options={properties}
    className="basic-multi-select"
    classNamePrefix="select"
    onChange={handleChangeProperties}
/>

The defaultValue is not showing anything.

The log, at first both properties and selectedProps are empty. Then, the second log it has values: Properties:

[
   (3) […]
​
0: Object { value: 2618, label: "Prop 1" }
​
1: Object { value: 2309, label: "Prop 2" }
​
2: Object { value: 2192, label: "Prop 3" }
​​
length: 3
​
<prototype>: Array []

selectedProps:

[
  {
    "value": 2618,
    "label": "Prop 1"
  },
  {
    "value": 2192,
    "label": "Prop 3"
  }
]

If I hard code he defaultValue it works, but not with the data coming from the variable.

1
why are you using useEffect? can't you do useState(props.location.user.properties)?Mr. A
I initiate the state as empty and the useEffect set the state data if the props.location.user is defined. Otherwise, I redirect the page.myTest532 myTest532

1 Answers

1
votes

Try this example, you could assign the initial state when declaring it Code Sandbox