Keep react component hover state in redux
Combine the reducer under the
hover state tree:
;;const app =;;
Create a component that has a
;;const MyHoverableComponent =hovered // managed by redux-hoveronMouseEnteronMouseLeaveconst style =background: hovered ? 'red' : 'blue';return<divstyle=styleonClick=onClickonMouseEnter=onMouseEnteronMouseLeave=onMouseLeave>Hover This</div>;;MyHoverableComponentpropTypes =hoverId: PropTypeshovered: PropTypesboolonMouseEnter: PropTypesfunconMouseLeave: PropTypesfunc;MyHoverableComponent;
MyHoverableComponent on the page and set a
;;const App =<div><MyHoverableComponent hoverId='myComponent'/><MyHoverableComponent hoverId='myOtherComponent'/></div>;;
The hovered prop is set to
MyHoverableComponent when the mouse is hovering over it. Otherwise it's set to false.
As long as id's are different, they'll be independently hoverable. The above example sets the strings manually, but you could also use a
This also means that ids with the same value will all get the hover state applied when any of them are hovered.
MyHoverableComponent is cloned with
This keeps the number of elements on the page minimal but adds a little overhead to clone the hoverable component.
Manually Dispatching Actions For Hover Or Unhover
Sometimes there's cases where manually dispatching an action might be necessary. A good example is a button that removes itself (clearing a todo list item for example). The actions are exposed for this purpose so they can be dispatched:
;const REMOVE_TODO = 'REMOVE_TODO';const removeTodo =Promiseall;