skip to Main Content

I have an array of values, and i am looping the array to display in Select Option

     <Form.Item label="Status">
        <Select
          value={user.status}
          onChange={handleStatusChange}
        >
          {status.map((item, index) => (
            <Select.Option key={index} value={item.status}>
              {item.name}
            </Select.Option>
          ))}
        </Select>
      </Form.Item>

I want to "None" to be displayed by default when nothing is selected or when the value of the mapped item is null.

In other words, i want none to be the selected option when status is null or undefined.
I am using antd

2

Answers


  1. To display an empty value, you will have to add displayEmpty to the Select, combined with renderValue.

          <Form.Item label="Status">
            <Select
              value={user.status}
              onChange={handleStatusChange}
              displayEmpty
              renderValue={
                (value) => {
                  return value || 'None'
                }
              }
            >
              {status.map((item, index) => (
                <Select.Option key={index} value={item.status}>
                  {item.name}
                </Select.Option>
              ))}
            </Select>
          </Form.Item>
    
    Login or Signup to reply.
  2. You can return the corresponding noption depending on the element value:

    {status.map((item, index) => {
      console.log(item);
      const itemNameOrNone = item ? (
        <option key={index} value={item.status}>
          {item.name}
        </option>
      ) : (
        <option key={index} value="None">
          None
        </option>
      );
    
      return itemNameOrNone;
    })};
    

    or just

    <option key={index} value={item ? item?.status : "none"}>
      {item ? item.name : "None"}
    </option>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search