article

Saturday, September 25, 2021

ReactJS MultiSelect dropdown

ReactJS MultiSelect dropdown

Install react-select package

npm install react-select
C:\reactdev\myreactdev>npm install react-select

import Select from 'react-select';

src/index.js
//src/index.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';

ReactDOM.render(
  <App />,
  document.getElementById('root')
)
public/index.html
//public/index.html
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>ReactJS </title>
  </head>
  <body>
    <div id="root"></div>
</body>
</html>
src/App.js
//src/App.js
import React, { useState } from 'react';
import Select from 'react-select';

function App() {
  const data = [
    {
      value: 1,
      label: "Python"
    },
    {
      value: 2,
      label: "Swift"
    },
    {
      value: 3,
      label: "Javascript"
    },
    {
      value: 4,
      label: "PHP"
    },
    {
      value: 5,
      label: "C#"
    },
    {
      value: 6,
      label: "Go"
    }
  ];

  const [selectedOption, setSelectedOption] = useState(null);

  // handle onChange event of the dropdown
  const handleChange = e => {
    setSelectedOption(e);
  }

  return (
    <div className="App">
      <b>MultiSelect Dropdown</b><br />

      <Select
        isMulti
        placeholder="Select Option"
        value={selectedOption} 
        options={data} // list of the data
        onChange={handleChange} // assign onChange function
      />

      {selectedOption && <div style={{ marginTop: 20, lineHeight: '25px' }}>
        <b>Selected Options</b><br />
        <pre>{JSON.stringify(selectedOption, null, 2)}</pre>
      </div>}
    </div>
  );
}
export default App;

Related Post