2

I'm new to React and I wanted to create a dropdown which can select multiple values. For that I used the react-select plugin. In my React dev tool the selected values are getting stored but I'm not able to display all the selected values. Any help is highly appreciated. TIA

import React, { useState } from "react";
import Select from 'react-select'

const options = [
    { value: 'React', label: 'React' },
    { value: 'Vue', label: 'Vue' },
    { value: 'Angular', label: 'Angular' },
    { value: 'Java', label: 'Java' },
  ]

    const [skills, setSkills] = useState([]);

    const handleChange = (skill) => {
        setSkills({skill})
        console.log("skills", skill);
    }
    
    return (
        <>
           <h2>Please select all your skills</h2>
             <form>
                 <Select 
                    options={options} 
                    onChange={handleChange}
                    isMulti={true}
                    value={value}
                 />
                <button>Next</button> 
            </form>

        </>
    )
}

export default UserSkills;

When I'm commenting isMulti prop, I'm getting that one selected value, but I'm not getting anything with isMulti prop.

1
  • you are passing value prop, whic will assign the value, instead you need to pass options prop which lists all choices for the select. You can refer getting started code in the docs Commented Dec 23, 2020 at 5:59

1 Answer 1

3

You are controlling the Select component by giving it a value, and since you are not updating value in the handleChange function it will not be updated.

You could use the skills array as value instead and it will update as expected.

CodeSandbox

const options = [
  { value: "React", label: "React" },
  { value: "Vue", label: "Vue" },
  { value: "Angular", label: "Angular" },
  { value: "Java", label: "Java" }
];

function UserSkills() {
  const [skills, setSkills] = useState([]);

  const handleChange = (skills) => {
    setSkills(skills || []);
  };

  return (
    <>
      <h2>Please select all your skills</h2>
      <form>
        <Select
          options={options}
          onChange={handleChange}
          value={skills}
          isMulti
        />
        <button>Next</button>
      </form>
    </>
  );
}

export default UserSkills;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.