Hi everyone I am having an issue with the react-select onBlur function, I did a lot of research and looked into relevant git issues but still couldn't find an answer. OnBlur function does not get the selected values, the value in onBlur is shown undefined. if the answer available please suggest me. Thanks for the help
Codesanbox Link for reference:
import React, { useState } from "react";
import Select from "react-select";
import "./styles.css";
export default function App() {
  const [value, setValue] = useState();
  const options = [
    {
      label: "first option",
      value: 1
    },
    {
      label: "second option",
      value: 2
    },
    {
      label: "third option",
      value: 3
    }
  ];
  const onSelect = (value) => {
    setValue(value);
  };
  const onBlurValue = (value) => {
    console.log(value);
  };
  return (
    <div>
      <Select
        value={options.label}
        options={options}
        onChange={onSelect}
        blurInputOnSelect
        onBlur={onBlurValue}
      />
    </div>
  );
}
                Consider this code (check out the comments):
import React, { useState } from "react";
import Select from "react-select";
import "./styles.css";
export default function App() {  
  const [value, setValue] = useState();
  const options = [
    {
      label: "first option",
      value: 1
    },
    {
      label: "second option",
      value: 2
    },
    {
      label: "third option",
      value: 3
    }
  ];
  // destructuring the object to get 'value' property
  // (the passed object looks like { label, value } )
  const onSelect = ({value}) => {
    // here the 'value' variable is being set
    console.debug("selected value:", value )
    setValue(value);
  };
  // destructuring event object to get 'target' property
  const onBlurValue = ({target}) => {
    console.log("onBlur target value:", target.value);
    // the value is not updated yet, so it holds the previously set value
    console.log("onBlur value:", value || "undefined");
  };
  return (
    <div>
      Current value is: {value || "undefined" }
      <Select
        // the value prop does nothing here
        // value={options.label}
        options={options}
        onChange={onSelect}
        blurInputOnSelect
        onBlur={onBlurValue}
      />
    </div>
  );
}
As @a.mola said - the setValue hook is asynchronous, and the value variable isn't updated yet when the onBlur event fires, so it holds the previously set value.
I'm not sure about what are you trying to achieve within the onBlur event, it may not be the right place to do it.
If you need to output the value somehow - you can do so within the return part (as is done in code above).
If you need to validate the value or do something based on its newly selected value - you can do so within the onSelect function.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With