0.1.0-alpha.3 • Published 7 years ago

redux-hover v0.1.0-alpha.3

Weekly downloads
4
License
MIT
Repository
github
Last release
7 years ago

redux-hover

Why store hover state in Redux?

Let's say you have a line chart and a table, and when the user hovers over a table cell, you want to highlight the related point. We can do this with redux-hover.

function Chart() {
  return (
    <g>
      <HoverEffect id="example">
        {show => (
          <circle
            className={classNames(
              styles.point,
              show && styles['point--highlight']
            )}
          />
        )}
      </HoverEffect>
    </g>
  );
}

function Table() {
  return (
    <table>
      <tbody>
        <tr>
          <Hoverable id="example">
            <td>
              Table cell
            </td>
          </Hoverable>
        </tr>
      </tbody>
    </table>
  );
}

Hoverable and HoverEffect are Redux containers.

  • Hoverable attaches mouseenter and mouseleave listeners to its child.
  • HoverEffect shows or hides its child based on whether the user is currently hovering the related Hoverable.

The nice thing about this model is that a single Hoverable can trigger any number of related HoverEffects. For example, let's say the chart is split into two views of the same data. You can use two HoverEffects to highlight the related data point in each view.

This library also supports toggles (when a component is clicked, the flag is flipped). This is useful for things like dropdowns and inline dialogs. The API for hovers and toggles is very similar.

Usage

import { Hoverable, HoverEffect, reducer, Toggleable, ToggleEffect } from 'redux-hover';

// configureStore
const reducer = combineReducers({
  hover: reducer,
});

// hover trigger
<Hoverable id="hover">
  <div>
    Hover me
  </div>
</Hoverable>

// hover effect (pass flag to child function)
<HoverEffect id="hover">
  {show => (
    <div
      style={{ opacity: show ? 1 : 0.5 }}
    >
      Hover effect
    </div>
  )}
</HoverEffect>

// hover effect (show or hide child)
// If HoverEffect's child is a function, the hover state is passed to the child as a flag. This is the most flexible option.
// If HoverEffect's child is a node, the child is shown or hidden based on the hover state. This can be used to implement tooltips.
<HoverEffect id="tooltip">
  <div>
    Tooltip
  </div>
</HoverEffect>

// toggle trigger
<Toggleable id="dropdown">
  <div>
    Dropdown button
  </div>
</Toggleable>

// toggle effect
<ToggleEffect id="dropdown">
  <div>
    Dropdown panel
  </div>
</ToggleEffect>

Setup

npm install
npm start
# Visit http://localhost:8080