score:1
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.
score:0
score:0
The prop blurInputOnSelect
you pass to the Select
component, removes focus from the Component after the value has changed and since useState
and setState
are asynchronous, the value isn't updated immediately. That is why the value logged to the console is undefined
.
The solution will be to remove the blurInputOnSelect
prop from the Select
component
score:1
You can add an instance variable to store the selected value (maybe not the best solution but it should work)
export default function App() {
const [value, setValue] = useState();
const valueRef = useRef();
const onSelect = value => {
valueRef.current = value;
setValue(value);
};
const onBlurValue = () => {
console.log(valueRef.current);
};
return (
<div>
<Select
value={value}
options={options}
onChange={onSelect}
blurInputOnSelect
onBlur={onBlurValue}
/>
</div>
);
}
The problem with this solution is that you store the selected value in two places (the state variable and the reference instance variable).
The question is, why do you need the get the selected value inside the onBlur handler ? The onChange handler might be sufficient in your case, isn't it ?
Source: stackoverflow.com
Related Query
- React select npm onBlur function returns An error
- react select error on upgrade: TypeError: dispatcher.useInsertionEffect is not a function
- React js error in a simple function that takes an array and returns a random value
- function that returns a select with options, using React
- Invalid hook call error when using React function component from npm package
- Error with basic React Example: Uncaught TypeError: undefined is not a function
- Symlinking react modules with npm link for local development gives error
- How to receive select value in handlesubmit function with formik react js?
- React 0.14.2 error - Super expression must either be null or a function
- npm start on new create-react-app build returns ELIFECYCLE error
- React JS : history.push is not a function error and it isn't navigating to a different page onclick of swal
- findDOMNode error on React material-ui select menu
- React functional component vs. plain-old JS function that returns React element
- React error when using audio.play() function
- React Error : __WEBPACK_IMPORTED_MODULE_4_jquery___default(...)(...).modal is not a function
- React App returns error after refresh
- React @material-ui/core - v4.11.0 - "the createMuiTheme function was renamed to createTheme" console error
- React npm error “npm ERR! code ELIFECYCLE” when I do npm start
- Error when trying to use function that returns a function that returns a HOC (a la Redux Connect)
- React Using useState/Hooks In HOC Causes Error "Hooks can only be called inside of the body of a function component"
- React .map() is not a function error
- React this.setState With Arrow Function Causes Error In Console
- Symbol is not a function react enzyme i18n error
- Receiving error - Hooks can only be called inside of the body of a function component when implementing React Spring basic example
- There is TypeError (0 , _ColorReducer.color) is not a function error in React + Redux code
- React App: Why I get an error when I try to run npm start script?
- React component function returning JSX causes error when used in render method of ES6 class React component
- React input text default value and onblur function make input text read only
- React function returns undefined
- Typescript returns error when a function type is FunctionalComponent, but not for arrow function
More Query from same tag
- Hash router works in production but browser router doesn't in react webpack app
- useRouter().push() refreshing the page in next js
- need to find a code to call two functions when div is clicked in react
- How can I functionally autofill props for a React Component?
- Why my react datatable is rendering all data at once also search bar is not working?
- React: loading and updating nested resources when URI changes without excess duplication?
- React get request without refreshing the page
- semantic-ui-react how to use form group inside a grid
- how to write correctly - js in html in return statement
- React material-ui KeyboardDatePicker and Formik not working
- How can I set a global context in Next.js without getting a "Text content did not match" error?
- How to conditionally add classNames to components in React?
- Dependency cycle issue when using Styled Components alongside compound component pattern
- Master Check Box in AG Grid on any column
- Reload table data when select menu item is changed
- React Router browserHistory push and anchors
- Why React says "Logout is not a function ?"
- How to retrieve and display images in reactjs that are stored on the server side using multer and the path is stored in the database
- Automatically adjust height of iframe using React Hooks
- React - Displaying a loading spinner for a minimum duration
- Fetch creating infinite loop
- Bar items in Recharts Stacked Bar Graph do not render when being returned through iteration
- What is nextprops in UNSAFE_componentWillReceiveProps and convert it into React Hook Functional component?
- update charjs dataset using react library
- How to configure WebPack DevServer to handle the POST request in React JS?
- How to debug failed to fetch in react-admin app
- webpack bundle.js not found - 404 error
- use useRef to get updated height on children changed
- Module not found Error: You attempted to import which falls outside of the project src/ directory. Relative imports outside of src/ are not supported
- how to render divs dynamically based on the number of items