Home > Blockchain >  REACT - Turn a selection from a dropdown to a tag label
REACT - Turn a selection from a dropdown to a tag label

Time:04-26

Is there a way to turn a selection from a dropdown to a tag with the appropriate color (see the image).

export default function MenuItemDisplay() {
...
  const colourStyles = {
    singleValue: (provided, { data }) => ({
      ...provided,
      backgroundColor:
        data.value === "Good"
          ? "#36B37E"
          : data.value === "Medium"
          ? "#FF8B00"
          : data.value === "Bad"
          ? "#FF5630"
          : ""
    })
  };
...
  return (
      ...
          <CustomDropdown
            style={styles.select}
            options={TASTE}
            defaultValue={TASTE.find((t) => t.label === item.taste)}
            styleSelect={colourStyles}
          />
        </div> 
       ...      
  );
}

export default function CustomDropdown({ className, style, options, styleSelect, defaultValue, isMulti }) {
    return <div style={style}>
        <Select className={className} styles={styleSelect} options={options} defaultValue={defaultValue} isMulti={isMulti} />
    </div>
}

Here is the picture to get the idea:enter image description here

Here is the code

CodePudding user response:

What you can do is having another Tag component that replace the dropdown each time you select an element:

export default function CustomDropdown({
  style,
  options,
  styleSelect,
  defaultValue
}) {
  const [selected, setSelected] = React.useState(defaultValue);
  const backgroundColor = styleSelect?.(selected?.label) ?? "grey";
  
  const Tag = () => {
    return (
      <div style={{display: "flex", justifyContent:"space-around", padding: "0.2em",backgroundColor: backgroundColor, borderRadius: "2px", color:"white"}}>
        {selected.label}
        <button
        style={{backgroundColor: "transparent", color:"white", border: "none", cursor: "pointer"}} 
        onClick={() => setSelected(null)}>x</button>
      </div>
    )
  }
  return (
    <div style={style}>
      {selected ?
       <Tag />
       :
      <Select
        value={selected}
        onChange={setSelected}
        options={options}
      />
      }
      
    </div>
  );
}

Ideally you should create a proper file for the Tag component and pass the selected prop to the component.

Also I changed the implementation of colourStyles and made it a function that returns the proper color based on the selection:

const colourStyles = (selected) => {
     switch(selected){
       case "Good": 
        return "#36B37E";
       case "Medium": 
        return "#FF8B00";
       case "Bad": 
        return "#FF5630";
       default:
         return ""
     }
  };
  • Related