I’m using react-select with isMulti, there is a list of options. I want to display few options by default selected if matched with given array values.
import React, { useState } from "react";
import "./styles.css";
import Select from "react-select";
export default function App() {
const options = [
{
value: "one",
label: "One Label"
},
{
value: "two",
label: "Two Label"
},
{
value: "three",
label: "Three Label"
},
{
value: "four",
label: "Four Label"
}
];
const getSelected = ["two", "four"];
const [list, setList] = useState(options);
list.map((val: any) => {
getSelected.map((selectedVal: any) => {
if (val.value === selectedVal) {
setList(val);
}
});
});
return (
<div className="App">
<Select options={list} isMulti />
</div>
);
}
Thanks for your Efforts!
4
Answers
Try the following code:
Two mistakes here.
First, import useEffect.
import React, { useState, useEffect } from "react";
then replace this
with
in this code we are using useEffect so that we run this code only when list changes, that’s why we have to add list to dependency array of
useEffect
then we are filtering the selectedList for values that are in
getSelected
array.Your aim is to filter array results, but
Array.map()
is not supposed to be used for that.Here is good explanation of array methods
How to Use map(), filter(), and reduce() in JavaScript
To summarize:
filter()
is used to filter an arraymap()
is used to transform array values into some other valuesUse defaultValue Prop:
Instead of directly modifying the list state inside the map function, you could create a new array of selected options and then set it as the state value. Then use the useEffect hook to populate selectedOptions with the options that match the values in the getSelected array. This effect runs once when the component mounts. In the Select component, you can set the options prop to the original list of options and the value prop to selectedOptions. Also Provide an onChange handler to update the selectedOptions state when the user selects or deselects options.