Pre-selected value in react-select component

17 Views Asked by At

I have a table with my content list. The content can be updated by clicking on the pencil icon. While the values to be edited come in normal inputs, they do not come to the react-select component. There is no information about this in the official document. Assigning state to inputValue and value values did not work either. And the last thing, im using react-hook-form and controlling react-select input in I would be very happy if anyone who has experience with react-select can help.

const handleEdit = (item) => {      
  setValue("type", item.type);     
};

<Controller
  name="type"
  control={control}
  render={({ field }) => (
    <Select
     {...field}
     options={[
       { value: "Brand", label: "Brand" },
       { value: "Category", label: "Category" },
       { value: "Product", label: "Product" },
     ]}
     placeholder="Type"
     onChange={handleTypeChange}
    />
 />
1

There are 1 best solutions below

0
Kayahan Kahrıman On

I finally solved the problem. I created a separate state for edits and kept the values there. The main point was to send the values as objects. I sent them to as {label: "Label", value: "Value"} and the problem was fixed. Of course, when I sent it like this, the label of Select was not updated. So I couldn't select a new value when I pressed the dropdown, so I had to update the onChange function. If there is an edited value, I showed this value in onChange. I am giving the code below, maybe someone needs it.

const [editedType, setEditedType] = useState({});

const handleEdit = (item) => {
  setEditedType({ label: item.type, value: item.type });      
};

const handleTypeChange = (type) => {
  setType(type);
  if (editedType) {
    setEditedType({ label: type.value, value: type.value });
  }
};

<Controller
  name="type"
  control={control}
  render={({ field }) => (
    <Select
    {...field}
    options={[
      { value: "Brand", label: "Brand" },
      { value: "Category", label: "Category" },
      { value: "Product", label: "Product" },
    ]}
    placeholder="Type"
    onChange={handleTypeChange}
    value={editedType ? editedType : value}
  />