Search code examples
javascriptcssreactjsantd

AntDesign select menu, want to only show part of the option when selected


So i have this AntDesign Select menu

<CustomSelect defaultValue={weeklyImp} dropdownMatchSelectWidth={180} dropdownStyle={{textAlign: "center"}} onChange={handleWeeklyImpChange}>
       <Option value="0" >0 - red</Option>
       <Option value="1" >1 - green</Option>
       <Option value="2">2 - blue (after red)</Option>
</CustomSelect>

Now the list of options as you can see is 0 - red etc. However when i click on 1 - green for example, I want the value written inside that select box to be just 1.

Is that something weird to ask? I cant really find it anywhere in the Select docs


Solution

  • Create a state like this

    const [selectedColor, setSelectedColor] = useState();
    

    You will also need a function like this

    const funcShowOnlyPhoneCode = (value) => {
        setSelectedCode(`${value.substr(0,1)}`);
        console.log('value: ', value);
        return value;
    };
    

    Then in the JSX you add onChange={funcShowOnlyPhoneCode}

    <CustomSelect onChange={funcShowOnlyPhoneCode} defaultValue={selectedColor} dropdownMatchSelectWidth={180} dropdownStyle={{textAlign: "center"}} onChange={handleWeeklyImpChange}>
      <Option value="0" >0 - red</Option>
      <Option value="1" >1 - green</Option>
      <Option value="2">2 - blue (after red)</Option>
    </CustomSelect>