skip to Main Content

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


  1. Try the following code:

    import React, {useEffect, 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);
    
      useEffect(() => {
        setList(list.filter((val) => getSelected.includes(val.value)))
      }, []);
    
      return (
          <div className="App">
            <Select options={list} isMulti />
          </div>
      );
    }
    
    Login or Signup to reply.
  2. Two mistakes here.

    1. You’re setting only 1 value from within the map.
    2. You’re doing that on every render

    First, import useEffect.
    import React, { useState, useEffect } from "react";

    then replace this

      list.map((val: any) => {
        getSelected.map((selectedVal: any) => {
          if (val.value === selectedVal) {
            setList(val);
          }
        });
      });
    

    with

    useEffect(() => {
      const selectedValues = list.filter((val: any) => {
        return getSelected.includes(val)
      });
      setList(seletedValues);
    },[list]) 
    
    

    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:

    1. filter() is used to filter an array
    2. map() is used to transform array values into some other values
    Login or Signup to reply.
  3. Use defaultValue Prop:

    <Select defaultValue={[getSelected[0], getSelected[1]]} isMulti />
    
    Login or Signup to reply.
  4. 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.

    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 [selectedOptions, setSelectedOptions] = useState([])
    
      useEffect(() => {
        const defaultSelectedOptions = options.filter((option) =>
          getSelected.includes(option.value)
        )
        setSelectedOptions(defaultSelectedOptions)
      }, []) // Empty dependency array ensures this effect runs only once on component mount
    
      return (
        <div className="App">
          <Select
            options={options}
            isMulti
            value={selectedOptions}
            onChange={(selected) => setSelectedOptions(selected)}
          />
        </div>
      )
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search