Home > Back-end >  REACT-SELECT defaultValue in CustomDropdown not working
REACT-SELECT defaultValue in CustomDropdown not working

Time:04-17

I want the default value of my dropdown to be defaultValue={item.taste} (value from match.json) but it's not working... (go to /menu/Menu1 and Pea Soup)

import Select from "react-select";

export default function CustomDropdown({ style, options, defaultValue }) {
  return (
    <div style={style}>
      <Select options={options} defaultValue={defaultValue} />
    </div>
  );
}

MenuItemDisplay:

export default function MenuItemDisplay() {

  const { menuId, itemId } = useParams();
  const { match } = JsonData;    
  const matchData = match.find((el) => el._id_menu === menuId)?._ids ?? [];
  const item = matchData.find((el) => el._id === itemId);

  const styles = {
    select: {
      width: "100%",
      maxWidth: 150
    }
  };
  const TASTE = [
    { label: "Good", value: "Good" },
    { label: "Medium", value: "Medium" },
    { label: "Bad", value: "Bad" }
  ];
...   

  return (
    <>
        <div className="TextStyle">
          {"Taste "}
          <CustomDropdown
            style={styles.select}
            options={TASTE}
            defaultValue={item.taste}
           //The default value is not working only if it's 
           //TASTE[0]
          />
        </div>
        ...
    </>
  );
}

Here the link for the code

CodePudding user response:

As defaultValue you need to pass one of the objects of the TASTE array. You can do this:

<CustomDropdown
  style={styles.select}
  options={TASTE}
  defaultValue={TASTE.find(t => t.label === item.taste)}
/>
  • Related