• Stars
    star
    296
  • Rank 140,464 (Top 3 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created over 7 years ago
  • Updated over 1 year ago

Reviews

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

Repository Details

Bind events to state. Works with Preact and React.

linkState

Create an Event handler function that sets a given state property. Works with preact and react.

  • Tiny: ~300 bytes of ES3 gzipped
  • Familiar: it's just a function that does what you would have done manually
  • Standalone: one function, no dependencies, works everywhere

๐Ÿค” Why?

linkState() is memoized: it only creates a handler once for each (key, eventPath) combination.

This is important for performance, because it prevents handler thrashing and avoids allocations during render.


Table of Contents


Installation

npm install --save linkstate

The UMD build is also available on unpkg:

<script src="//unpkg.com/linkstate/dist/linkstate.umd.js"></script>

This exposes the linkState() function as a global.


How It Works

It's important to understand what linkState does in order to use it comfortably.

linkState(component, statePath, [valuePath])

  • component: the Component instance to call setState() on
  • statePath: a key/path to update in state - can be dot-notated for deep keys
  • valuePath: optional key/path into the event object at which to retrieve the new state value

It's easiest to understand these arguments by looking at a simplified implementation of linkState itself:

function linkState(component, statePath, valuePath) {
  return event => {
    let update = {};
    update[statePath] = event[valuePath];
    component.setState(update);
  };
}

In reality, accounting for dot-notated paths makes this trickier, but the result is the same.

Here's two equivalent event handlers, one created manually and one created with linkState:

handleInput = e => {
  this.setState({ foo: e.target.value })
}

handleInput = linkState(this, 'foo')

Notice how we didn't specify the event path - if omitted, linkState() will use the checked or value property of the event target, based on its type.

Usage

Standard usage is a function that returns an event handler to update state:

import linkState from 'linkstate';

class Foo extends Component {
  state = {
    text: ''
  };
  render(props, state) {
    return (
      <input
        value={state.text}
        onInput={linkState(this, 'text')}
      />
    );
  }
}

You can also use it as a polyfill. This emulates the behavior of Preact 7.x, which provided linkState() as a method on its Component class. Since you're then calling linkState() as a method of the component instance, you won't have to pass in component as an argument:

import 'linkstate/polyfill';

// Component.prototype.linkState is now installed!

class Foo extends Component {
  state = {
    text: ''
  };
  render(props, state) {
    return (
      <input
        value={state.text}
        onInput={this.linkState('text')}
      />
    );
  }
}

Contribute

First off, thanks for taking the time to contribute! Now, take a moment to be sure your contributions make sense to everyone else.

Reporting Issues

Found a problem? Want a new feature? First of all see if your issue or idea has already been reported. If it hasn't, just open a new clear and descriptive issue.

Submitting pull requests

Pull requests are the greatest contributions, so be sure they are focused in scope, and do avoid unrelated commits.

๐Ÿ’ Remember: size is the #1 priority.

Every byte counts! PR's can't be merged if they increase the output size much.

  • Fork it!
  • Clone your fork: git clone https://github.com/<your-username>/linkstate
  • Navigate to the newly cloned directory: cd linkstate
  • Create a new branch for the new feature: git checkout -b my-new-feature
  • Install the tools necessary for development: npm install
  • Make your changes.
  • npm run build to verify your change doesn't increase output size.
  • npm test to make sure your change doesn't break anything.
  • Commit your changes: git commit -am 'Add some feature'
  • Push to the branch: git push origin my-new-feature
  • Submit a pull request with full remarks documenting your changes.

License

MIT License ยฉ Jason Miller

More Repositories

1

mitt

๐ŸฅŠ Tiny 200 byte functional event emitter / pubsub.
TypeScript
9,030
star
2

htm

Hyperscript Tagged Markup: JSX alternative using standard tagged templates, with compiler support.
JavaScript
8,661
star
3

microbundle

๐Ÿ“ฆ Zero-configuration bundler for tiny modules.
JavaScript
8,055
star
4

unfetch

๐Ÿ• Bare minimum 500b fetch polyfill.
JavaScript
5,637
star
5

greenlet

๐ŸฆŽ Move an async function into its own thread.
JavaScript
4,621
star
6

workerize

๐Ÿ—๏ธ Run a module in a Web Worker.
JavaScript
4,287
star
7

redaxios

The Axios API, as an 800 byte Fetch wrapper.
JavaScript
4,131
star
8

unistore

๐ŸŒถ 350b / 650b state container with component actions for Preact & React
JavaScript
2,865
star
9

express-es6-rest-api

๐Ÿ”‹ Starter project for an ES6 RESTful Express API.
JavaScript
2,460
star
10

workerize-loader

๐Ÿ—๏ธ Automatically move a module into a Web Worker (Webpack loader)
JavaScript
2,283
star
11

snarkdown

๐Ÿ˜ผ A snarky 1kb Markdown parser written in JavaScript
JavaScript
2,180
star
12

stockroom

๐Ÿ—ƒ Offload your store management to a worker easily.
JavaScript
1,758
star
13

dlv

Safe deep property access in 120 bytes. x = dlv(obj, 'a.b.x')
JavaScript
1,217
star
14

karmatic

๐Ÿฆ‘ Easy automatic (headless) browser testing with Jest's API, but powered by Karma & Webpack.
JavaScript
1,181
star
15

decko

๐Ÿ’จ The 3 most useful ES7 decorators: bind, debounce and memoize
JavaScript
1,038
star
16

preact-boilerplate

๐ŸŽธ Ready-to-rock Preact starter project, powered by Webpack.
JavaScript
976
star
17

web-worker

Consistent Web Workers in browser and Node.
JavaScript
949
star
18

vhtml

Render JSX/Hyperscript to HTML strings, without VDOM ๐ŸŒˆ
JavaScript
740
star
19

histore

๐Ÿฌ 200b key-value store backed by navigation state
JavaScript
677
star
20

optimize-plugin

Optimized Webpack Bundling for Everyone. Intro โคต๏ธ
JavaScript
659
star
21

undom

๐Ÿฉ 1kb minimally viable DOM Document implementation
JavaScript
654
star
22

asyncro

โ›ต๏ธ Beautiful Array utilities for ESnext async/await ~
JavaScript
493
star
23

nextjs-preact-demo

Next.js 9.3 + Preact = 21kB
JavaScript
384
star
24

tags-input

๐Ÿ”– <input type="tags"> like magic
JavaScript
328
star
25

preact-redux

โžฟ Preact integration for Redux (no shim needed!)
JavaScript
288
star
26

task-worklet

Task Worklet: explainer, polyfill and demos.
JavaScript
275
star
27

jsdom-worker

๐Ÿ‘ทโ€โ™€๏ธ Use Web Workers in Jest / JSDOM ๐ŸŒˆ
JavaScript
273
star
28

preact-worker-demo

Demo of preact rendering an entire app in a Web Worker.
JavaScript
217
star
29

preact-virtual-list

๐Ÿ“‡ Virtual List that only renders visible items. Supports millions of rows.
JavaScript
215
star
30

jsxobj

Build JSON using JSX ๐ŸŒˆ (may contain blood magic)
JavaScript
214
star
31

preact-redux-example

๐Ÿ” Preact + Redux Example Project
JavaScript
201
star
32

preact-markup

โšก Render HTML5 as VDOM, with Components as Custom Elements!
JavaScript
195
star
33

simple-element-resize-detector

Observes element size changes using a hidden iframe
JavaScript
190
star
34

preact-mdl

๐Ÿ’ฅ A collection of Preact Components that encapsulate Google's Material Design Lite.
JavaScript
186
star
35

zero-to-preact

A Step-by-step Guide to Preact + Webpack 2, without boilerplate!
JavaScript
179
star
36

state-machine-component

โš™๏ธ State machine -powered components in 250 bytes
JavaScript
177
star
37

preact-portal

๐Ÿ“ก Render Preact components in (a) SPACE ๐ŸŒŒ ๐ŸŒ 
JavaScript
176
star
38

preact-photon

๐Ÿš€ Beautiful desktop apps with Preact + Photon โค๏ธ
JavaScript
173
star
39

preact-slots

๐Ÿ•ณ Render Preact trees into other Preact trees, like portals.
JavaScript
157
star
40

oss.ninja

๐Ÿ‘ฉโ€โš–๏ธ Dynamic licenses for your projects - no more LICENSE.txt!
JavaScript
146
star
41

preact-cycle

โ™ป๏ธ Minimal functional Virtual DOM rendering using Preact ๐Ÿšฒ
JavaScript
131
star
42

dropfox

๐ŸฆŠ ๐Ÿ“‚ A dropbox client powered by Preact, Electron and Photon
JavaScript
122
star
43

preact-scroll-viewport

Preact Component that renders homogeneous children only when visible
JavaScript
121
star
44

babel-preset-modernize

JavaScript
121
star
45

resource-router-middleware

๐Ÿšด Express REST resources as middleware mountable anywhere
JavaScript
120
star
46

object-diff-patch

JavaScript
103
star
47

preact-todomvc

๐Ÿ’ฃ TodoMVC done in Preact. Under 6kb and fast.
JavaScript
102
star
48

restful-mongoose

๐Ÿฆ Expose Mongoose models as RESTful Express resources.
JavaScript
90
star
49

modify-babel-preset

๐Ÿ’ซ Create a modified babel preset based on an an existing preset.
JavaScript
85
star
50

preact-without-babel

๐ŸŽ How to use Preact in (native) ES2015, without Babel or JSX.
JavaScript
79
star
51

preact-shadow-root

๐Ÿ•ด Render a Preact subtree into the Shadow DOM.
JavaScript
72
star
52

linkref

Like Linked State, but for Refs. Works with Preact and React.
JavaScript
61
star
53

preact-css-transition-group

Apply CSS transitions when adding or removing Preact components/elements
JavaScript
61
star
54

proptypes

๐Ÿ’‚โ€โ™‚๏ธ React's PropTypes, as a standalone module.
JavaScript
59
star
55

preact-token-input

๐Ÿ”– A text field that tokenizes input, for things like tags.
JavaScript
59
star
56

nectarine

๐Ÿ‘ A mobile web / Android app for Peach! (peach.cool) โšก
JavaScript
59
star
57

unified-element-properties-proposal

Unified Element Properties for the DOM
58
star
58

preact-jsx-chai

โœ… Add JSX assertions to Chai, with support for Preact Components.
JavaScript
56
star
59

preact-compat-example

๐Ÿšค Demo of preact-compat + react-toolbox to reduce build size by 95%.
JavaScript
52
star
60

preact-transition-group

transition-group ui component for preact
JavaScript
51
star
61

scroll-list

๐Ÿ“œ An infinitely scrollable list/datagrid. Handles millions of rows.
JavaScript
48
star
62

preact-in-es3

๐Ÿด How to use Preact without Babel, ES2015 or JSX.
JavaScript
46
star
63

rollup-plugin-preserve-shebang

Rollup plugin to automatically preserve shebangs in entry modules.
JavaScript
45
star
64

preact-cli-plugin-async

Preact CLI plugin that adds converts async/await to Promises.
JavaScript
44
star
65

preact-views

๐Ÿ“บ Named views for Preact, with easy-as-pie linking between them.
JavaScript
39
star
66

preact-richtextarea

๐Ÿ“ฐ A text field that supports HTML editing. ๐Ÿ“
JavaScript
39
star
67

react-router-4-test

Did you know you can use React Router with Preact, no -compat?
JavaScript
35
star
68

element-worklet

34
star
69

documentation-viewer

๐Ÿ“œ Hosted viewer for documentation.js JSON output.
JavaScript
34
star
70

sleeper

๐Ÿ˜ด REST abstraction so easy you could use it with your eyes closed. ๐Ÿ’ค
JavaScript
30
star
71

neatime

Returns a simple relative time string.
JavaScript
30
star
72

babel-preset-preact

Babel preset to transform JSX into h() calls
JavaScript
30
star
73

ama

Ask me stuff
28
star
74

htmlParser

Simple JavaScript HTML parser.
JavaScript
27
star
75

precharts

Just Recharts pre-aliased for Preact.
JavaScript
27
star
76

object-shape

Get a description of a JS object's shape.
JavaScript
24
star
77

eslint-config-developit

developit's generic eslint config for libraries
JavaScript
21
star
78

peach.cool

๐Ÿ‘ JavaScript library for Peach (peach.cool) โšก
JavaScript
21
star
79

progress-spinner

โŒš A simple, CSS-only indeterminate spinner custom element.
HTML
21
star
80

rollup-plugin-postprocess

๐ŸŽž Find & replace postprocessing for Rollup output
JavaScript
18
star
81

desky

18
star
82

jasonformat.com

My blog
JavaScript
18
star
83

preact-tap-event-plugin

โ˜๏ธ onTouchTap for preact
JavaScript
17
star
84

preact-svg

[DEPRECATED] ๐ŸŽจ Use inline <svg> in Preact 4 and prior. ๐ŸŒท
JavaScript
16
star
85

preact-styled-jsx-demo

Preact + styled-jsx = ๐Ÿ’ž
JavaScript
16
star
86

preact-vite-template

JavaScript
15
star
87

espz

JavaScript
13
star
88

microbundle-2

JavaScript
13
star
89

hazelnut

๐ŸŒฐ Tiny inline AMD registry.
JavaScript
12
star
90

puredom

๐Ÿ’ฒ Fast, chainable and exstensible JavaScript library for building web applications.
JavaScript
11
star
91

request-easy-cache

๐ŸŽ A simple, configurable & instantiable caching wrapper around request.
JavaScript
11
star
92

templeton

๐Ÿ’ช Templating like the other ones, but not at all like the other ones.
JavaScript
10
star
93

bamboo-status-svg

A web service that generates build badges for Bamboo plans.
JavaScript
9
star
94

ford.js

๐Ÿ‘” The library nobody wants but that is for some reason still mayor.
JavaScript
8
star
95

jasonp

An itty bitty JSONP module
JavaScript
7
star
96

browser-nativefs

Native File System API with legacy fallback in the browser
JavaScript
7
star
97

strip-dom-whitespace

Traverses the DOM to strip whitespace-only Text nodes
JavaScript
6
star
98

picomarkdown

Converts basic markdown to HTML.
JavaScript
6
star
99

babel-preset-es2015-minimal

๐Ÿ’„ Babel's es2015 preset in loose mode without frills.
JavaScript
5
star
100

esbench

ESBench Feedback (future public repo)
4
star