• Stars
    star
    1,048
  • Rank 43,968 (Top 0.9 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created almost 8 years ago
  • Updated over 6 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

🚧 Create an invisible perimeter around an element and respond when its breached.

react-perimeter 🚧

Create an invisible padding around an element and respond when its breached.

Usage Example

react-perimeter exports a single Perimeter component that will register a mousemove listener and calculate whether the current mouse position is within a padding.

The padding will be calculated using getBoundingClientRect and the padding prop, which lets you define "padding" for the perimeter.

<Perimeter
  onBreach={this.prefetch}
  padding={60}>
  <button onClick={this.fetch}>Load More</button>
</Perimeter>

Perimeter by default will wrap its children in a span and use that to calculate the boundries. If you want to avoid the wrapping span, or you want the padding to be calculated from another element, you can use a render callback.

<Perimeter
  onBreach={this.prefetch}
  padding={60}>
  {ref => (
    <button
      ref={ref}
      onClick={this.fetch}>Load More</button>
  )}
</Perimeter>

The render callback is passed a ref callback which should be passed to the ref prop of the element you want to use.

Installation

yarn add react-perimeter

API

Props

Property Type Default Description
padding number 0 The buffer around the element that defines the padding of the perimeter
onBreach () => void undefined A callback to be invoked when the perimeter is breached
once boolean false Whether the callback should only be invoked once (for example, when prefetching some data or chunks). If true all event listeners will be removed after onBreach is called.
mapListeners EventListener => EventListener undefined If provided, each event listeners (resize, mousemove) will be passed in, and the returned function will be used instead.

Debouncing or Throttling

You may want to debounce or throttle the mousemove and resize event listeners if you've profiled your application and determined that they are noticeably affecting your performance. You can do so using the mapListeners prop, which takes a function that should accept an event listener and return a new function to be used instead.

<Perimeter mapListeners={listener => debounce(listener, 20)}>

By letting you provide the mapped listener yourself, react-perimeter gives you full control over what debounce/throttle imeplementation you wish to use and its paramaters.

Deduping Event Listeners

If you use react-perimeter in multiple places in your application you may want to dedupe the internal event listeners.

react-perimiter integrates with react-listener-provider to make deduping easy. Simply yarn add react-listener-provider and wrap your application like this:

import ReactListenerProvider from 'react-listener-provider';
<ReactListenerProvider>
   <YourApp>
       <Perimeter />
   </YourApp>
</ReactListenerProvider>

Any <Perimeter> component you use inside of <ReactListenerProvider> will automatically use the global event listener provided by react-listener-provider instead of registering its own.

Prefetching or Preloading

react-perimeter shines especially bright when used to prefetch or preload other components. Here is a small example that uses react-loadable and react-router to preload a route chunk when the cursor gets near a link:

import React from 'react'
// Assume this is the component returned from `react-loadable`, not the page itself
import OtherPage from './routes/other-page'
import Perimeter from 'react-perimeter'
import { Link } from 'react-router'

const App = () => (
  <div>
    <h1>Home Page!</h1>
    <p>Here's some content</p>
    <Perimeter padding={100} onBreach={OtherPage.preload} once={true} >
      <Link to="other">Other Page</Link>
    </Perimeter>
  </div>
)

react-loadable provides an extremely useful static preload method that begins fetching the chunk for us. We pass this to onBreach so that the preloading begins as soon as the mouse is within 100 pixels of the Link component. We also pass in the once prop to tell react-perimeter that we only want to respond to the first breach. This means that, after the preload request has been issued, the listeners will be deregistered, removing any unneeded overhead.

We can go one step further and abstract this out into its own component, PreloadLink:

const PreloadLink = ({ to, children, preload }) => (
  <Perimeter padding={100} onBreach={preload.preload} once={true}>
    <Link to={to}>{children}</Link>
  </Perimeter>
)
<PreloadLink to="about" preload={AboutPage} />

More Repositories

1

react-copy-write

✍️ Immutable state with a mutable API
JavaScript
1,785
star
2

tinytime

⏰ A straightforward date and time formatter in <1kb
JavaScript
1,337
star
3

alder

A minimal implementation of the UNIX tree command with colors!
JavaScript
225
star
4

json-to-graphql

Create GraphQL schema from JSON files and APIs
JavaScript
191
star
5

ln.js

TypeScript
175
star
6

critical-reasonmling-slides

OCaml
66
star
7

twitter-required-alt-text

A Chrome extension that will not let you tweet images until you've added alt text.
JavaScript
49
star
8

react-is-deprecated

Adds an optional isDeprecated method to React.PropTypes
JavaScript
44
star
9

enzyme-adapter-preact

JavaScript
39
star
10

reason-chat-app

A web-based chat application built with ReasonML
OCaml
36
star
11

ssr-benchmarks

Simple benchmark testing time taken to render on the server
JavaScript
31
star
12

reason-vue

OCaml
28
star
13

rst-selector-parser

A CSS selector-based parser for React Standard Tree (RST) traversal.
JavaScript
19
star
14

algorithms-and-data-structures

JavaScript
17
star
15

react-mood

render components based on the mood of the user
16
star
16

preact-flow-example

Minimal example showing how to use Preact with Flow
JavaScript
15
star
17

unnamed-web-lang

Rust
13
star
18

mentorship-program

A working draft of a mentorship program for underrepresented groups in tech.
11
star
19

blog

TypeScript
10
star
20

react-tester

A testing utility for modern React applications
JavaScript
10
star
21

reason-react-dom

OCaml
9
star
22

react-relay-redux

Redux integrations for Relay
JavaScript
8
star
23

gist.scss

gist.scss lets users restyle embedded gists easily with Sass variablles to better match their site.
CSS
8
star
24

babel-rust

A source-to-source JavaScript compiler written in Rust. Not for production use.
7
star
25

ReasonCharts

Rust
6
star
26

together

JavaScript
6
star
27

accessible-wordle

TypeScript
6
star
28

microbe.js

A small, easy to use Node.js framework written in ES6
JavaScript
6
star
29

preact-blaze

JavaScript
5
star
30

compiler

Rust
5
star
31

reaction-diffusion

JavaScript
4
star
32

unique-random-at-depth

JavaScript
4
star
33

gradient-animation.scss

Sass mixin that lets anyone easily implement an animated background gradient.
CSS
4
star
34

pymessage

Send SMS or iMessages directly from the command line
Python
4
star
35

reactive

JavaScript
3
star
36

cached-validations

Create validation functions that cache results
JavaScript
3
star
37

graphql-client

JavaScript
3
star
38

set-state-middleware

JavaScript
3
star
39

defined-keys-only

JavaScript
3
star
40

bst

JavaScript
3
star
41

assert-report

A barebones test reporter in ~1.5kb with zero dependencies
JavaScript
3
star
42

saveourshelter

source code for the upcoming website, saveourshelter.info
HTML
3
star
43

AccessibilityNodeInfoRepoProject

Kotlin
2
star
44

scroll.js

JavaScript
2
star
45

git-branch

A small script to create a new git branch and push it to origin
Shell
2
star
46

linked-list

JavaScript
2
star
47

except

blacklist object properties
JavaScript
2
star
48

googlefontloader

A web interface that allows for quick and easy downloads of the Google Web Fonts. It uses the Github API to access Google's public repository.
JavaScript
2
star
49

grasp.js

general purpose front-end utility for DOM manipulation and templating
JavaScript
2
star
50

duxly

A redux helper/pattern to simplify the mapping of action constants and reducers
JavaScript
2
star
51

react-spectre

A React component library for spectre.css
JavaScript
2
star
52

mkdirps-brackets

Allows for bracket expansions to be used in paths for folder creation
JavaScript
2
star
53

old-coding-challenge

Code challenge that must be completed by developer candidates
JavaScript
2
star
54

www

HTML
1
star
55

remix-remark-slate-resolve-bug

TypeScript
1
star
56

aweary

1
star
57

assets

CSS
1
star
58

chrome-user-timings-bug

HTML
1
star
59

exercism

My solutions to some exercism.io problems
Rust
1
star
60

ngGeometry

Angular directive for a simple Three.JS scene
JavaScript
1
star
61

immutable-state

helpers for managing immutable state
JavaScript
1
star
62

enzyme-test-repo

A repo to clone/fork when you need to provide a repo of an issue with enzyme
JavaScript
1
star