hernandeΩ
hernandeΩ

Reputation: 89

React lose focus of select after click

I am using react antd component library and I am having trouble losing focus of the select after I select an item in the dropdown. I am thinking it needs to call a blur method so it loses focus but Im not sure.

Here is the codesandbox: https://codesandbox.io/s/sizes-antd4103-forked-81i3d

Steps to reproduce,

click the dropdown and select a name item in the dropdown. Then when the dropdown closes, click it again. The dropdown should show but it doesnt. The user needs to select outside of the dropdown then click it again. I need to make it so they can click the selet at any point and it shows the dropdown.

Upvotes: 0

Views: 5747

Answers (1)

vincenzopalazzo
vincenzopalazzo

Reputation: 1645

Because you don't need to use open and also, you have some additional error

dropdownRender={menu => (
          <div>
             {menu}
           </dive>}

the empty tag is frustrating to see, and it is not a good manner.

This is the complete code code

import React from "react";
import ReactDOM from "react-dom";
import "antd/dist/antd.css";
import "./index.css";
import { Select, Button } from "antd";
const { Option } = Select;

const children = [];
for (let i = 10; i < 36; i++) {
  children.push(<Option key={i.toString(36) + i}>{i.toString(36) + i}</Option>);
}

const SelectSizesDemo = () => {
  const [dropdown, setDropdown] = React.useState(false);

  function onChange(value) {
    console.log(`selected ${value}`);
    setDropdown(false);
  }

  function onBlur() {
    console.log("blur");
    setDropdown(false);
  }

  function onFocus() {
    console.log("focus");
    setDropdown(true);
  }

  function onSearch(val) {
    console.log("search:", val);
  }

  const handleClick = () => {
    setDropdown(!dropdown);
  };

  return (
    <>
      <Select
        showSearch
        style={{ width: 200 }}
        placeholder="Select a person"
        optionFilterProp="children"
        onChange={onChange}
        onFocus={onFocus}
        onBlur={onBlur}
        onSearch={onSearch}
        filterOption={(input, option) =>
          option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
        }
        open={dropdown}
        onDropdownVisibleChange={handleClick}
        dropdownRender={(menu) => (
          <div>
            {menu}
            <Button onClick={handleClick}>Close</Button>
          </div>
        )}
      >
        <Option value="jack">Jack</Option>
        <Option value="lucy">Lucy</Option>
        <Option value="tom">Tom</Option>
      </Select>
    </>
  );
};

ReactDOM.render(<SelectSizesDemo />, document.getElementById("container"));

Runnable version

Upvotes: 1

Related Questions