Adnan Arif
Adnan Arif

Reputation: 107

I want to show Multiselect options in simple text in reactjs using react-select

I want to show all of my options in simple text like "firstOption,secOption". I am using react-select. but i couldn't find any solution. Here's my code

import React from 'react';
import CreatableSelect from 'react-select/creatable';
const PersonalDetails =()=>{

const [selectedbusiness,setselectedbusiness] = useState([]);
const businessChange = (selectedbusiness) => {
 setselectedbusiness(selectedbusiness);
}

const businessType = [
       {  label: "Retailers", value: "Retailers" },
       { label: "Health Practioners", value: "Health Practioners" },
       {  label: "Distributors", value: "Distributors" },
       {  label: "Food Service", value: "Food Service" },
       {  label: "Manufacturers", value: "Manufacturers" },
       {  label: "Business Service", value: "Business Service" },
       {  label: "Investor", value: "Investor" },
       {  label: "Blogging", value: "Blogging" },

     ];

return(
  <>
<CreatableSelect 
  options={ businessType }
  className="form__field form-control"
  isMulti
  onChange={businessChange}
  styles={{ singleValue: (base) => ({ ...base, padding: 5, borderRadius: 5, background: selectedbusiness.value, color: 'white', display: 'flex' }) }}
   defaultValue={ selectedbusiness }
   name="selectedbusiness"
   closeMenuOnSelect={false}
   placeholder="Select Business Type"
   />
</>
)
}

Upvotes: 1

Views: 54

Answers (1)

Hemanath
Hemanath

Reputation: 1095

const showOptions = () => {
    const formattedOptions = selectedbusiness.map(business => business.label).join(',');
    // printing the options to the console
    console.log(formattedOptions);
}

you can iterate through selectedbusiness and get their label and use the join method to create a formatted options string.

return(
    <>
  <CreatableSelect 
    options={ businessType }
    className="form__field form-control"
    isMulti
    onChange={businessChange}
    styles={{ singleValue: (base) => ({ ...base, padding: 5, borderRadius: 5, background: selectedbusiness.value, color: 'white', display: 'flex' }) }}
     defaultValue={ selectedbusiness }
     name="selectedbusiness"
     closeMenuOnSelect={false}
     placeholder="Select Business Type"
     />
    <button type="button" onClick={showOptions}>Show options</button>
  </>
  )

Upvotes: 2

Related Questions