Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change selected value component in react-select

Is there any way to change the selected value component design, At my option menu, I show CscId and CscDesc but when I select the option, I only want to show CscId only. Is there any way to change the selected value component? I google for this one and it already took 1 day. Please Help me.

enter image description here

Here is my react-select

import React  from "react";
import Select from 'react-select';

const costcenterselect = ({ value, onChange, id, datasource }) => {    
  const formatOptionLabel = ({ CscID, CscDesc }) => (            
    <div style={{ display: "flex"}}>
      <div style={{width:'40%'}}>{CscID}</div>                
      <div>{CscDesc}</div>                
    </div>
  );  

  return (
    <div>
      <Select 
        id={id}
        menuIsOpen={true}    
        formatOptionLabel={formatOptionLabel}
        getOptionValue={option => `${option.CscID}`}
        options={datasource}
        onChange={onChange}
        defaultValue={value}        
      />
    </div>           
  )
}

export default costcenterselect;
like image 876
lwin Avatar asked Dec 17 '22 16:12

lwin


1 Answers

You can do it using formatOptionLabel itself. It has a second argument which provides you with meta information like context which you can use to conditionally render. Here is a working demo.

You can see that context === value allows you to render for selected value while context === menu renders for the options.

const formatOptionLabel = ({ CscID, CscDesc }, { context }) => {
    if (context === "value") {
      return <div>{CscID}</div>;
    } else if (context === "menu") {
      return (
        <div style={{ display: "flex" }}>
          <div style={{ width: "40%" }}>{CscID}</div>
          <div>{CscDesc}</div>
        </div>
      );
    }
  };
like image 109
ron4ex Avatar answered Dec 31 '22 02:12

ron4ex