Search code examples
javascriptreactjsantd

auto select onBlur in React JS using ant design Select component


I have the following code

I am trying to do the following. When the user types something in input it should be added into my array onBlur. That part was working well. Now besides adding to the array I want it automatically to be selected. How can Iimplement that?

    import React, { useState } from "react";
    import "antd/dist/antd.css";
    import "./index.css";
    import { Select } from "and";

    const { Option } = Select;
    const arr = ["1", "2", "3"];
    const App = () => {
      const [data, setData] = useState(arr);

      return (
       <>
      <Select
        mode="tags"
        size={"large"}
        placeholder="Please select"
        style={{
          width: "100%"
        }}
      >
        {data?.map((el) => (
          <Option key={el} value={el}>
            {el}
          </Option>
        ))}
         </Select>

          <input onBlur={(e) => setData([...data, e.target.value])} />
        </>
      );
    };

    export default App;


Please help me to resolve that problem.


Solution

  • You need to control both children (data) and value of the Select component.

    You can control Select component's state by using value and onChange props like this:

    import React, { useState } from "react";
    import "antd/dist/antd.css";
    import "./index.css";
    import { Select } from "antd";
    
    const { Option } = Select;
    const arr = ["1", "2", "3"];
    const App = () => {
      const [data, setData] = useState(arr);
      const [value, setValue] = useState([]);
    
      const handleTextBlurred = (e) => {
        const newVal = e.target.value;
        if (!data.includes(newVal)) {
          setData([...data, newVal]);
        }
        if (!value.includes(newVal)) {
          setValue([...value, newVal]);
        }
      };
    
      return (
        <>
          <Select
            mode="tags"
            size={"large"}
            placeholder="Please select"
            style={{
              width: "100%"
            }}
            value={value}
            onChange={(newVal) => setValue(newVal)}
          >
            {data?.map((el) => (
              <Option key={el} value={el}>
                {el}
              </Option>
            ))}
          </Select>
    
          <input onBlur={handleTextBlurred} />
        </>
      );
    };
    
    export default App;
    

    You can take a look at this forked sandbox for a live working example of this solution.