I'm using React, Redux, and React Router for an application and having trouble with using on onBlur
input event in tandem with a route change.
I have a "SearchResults" component that presents a list of internal links. SearchResults
only shows when the state searchActive
is true.
<div>
{props.searchActive ? <SearchResults /> : props.children}
</div>
SearchResults
has a list of links rendered in a loop...
<Link key={Math.random()} to={r.path}>{r.name}</Link>
The input for the search (another, independent component) sets searchActive
to true
during the onFocus
event and false
for the onBlur
event.
<input
onFocus={() => {
// dispatch Redux action (set "searchActive" to true)
props.startSearch();
}}
onBlur={() => {
// dispatch Redux action (set "searchActive" to false)
props.endSearch();
}}
/>
With this setup, when I click on a Link
, the route does not change. However, if include a setTimeout
, I get the desired behavior.
...
setTimeout(() => {
props.endSearch();
}, 400)
...
Update
The onBlur
action is hiding the SearchResults component and not registering the Link
click. Is there any way I can register the Link click before doing the onBlur
action?
Why isn't react-router registering the route change on Link
click when I dispatch a Redux action in the onBlur
callback?
Simply, because the onBlur
event is fired before the click
event is registered, i.e. your link disappears from the DOM before it can acknowledge it was clicked.
The onMouseDown
event is fired before the onBlur
event, so if you use it to initiate navigation, there is no need for magic timeouts.
Here's a fiddle to demonstrate: https://jsfiddle.net/bp80sg7w/2/
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