Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React-router not changing routes with input onBlur event

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?

like image 619
Himmel Avatar asked Aug 11 '16 00:08

Himmel


1 Answers

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/

like image 115
jakee Avatar answered Oct 23 '22 04:10

jakee