• Stars
    star
    1,024
  • Rank 43,147 (Top 0.9 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created almost 6 years ago
  • Updated about 1 year ago

Reviews

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

Repository Details

A set of tiny React components for handling state with render props.

A set of tiny, composable React components
for handling state with render props.


Why? · Principles · Examples · Documentation · Contributing!



react-values gives you a set of simple, composable helpers that let you build more complex, stateful UI components like toggles, dropdowns, lists, checkbox groups, popovers, tooltips, you name it!

It does this using a small render-prop-based API that exposes helpful transforms like toggle, increment, filter, etc. depending on the type of value, all based on JavaScripts native value types...

  • Any values provide simple transforms like set and clear.
  • Array values provide native methods like push, pop, filter, etc.
  • Boolean values provide toggle, which we've all re-implemented 100 times.
  • Date values provide really helpful transforms like setHours and incrementMonth.
  • Map values provide native methods like set, delete and clear.
  • Number values provide increment and decrement, which have also been re-written in every codebase ever.
  • Object values provide helpful transforms like set, unset and assign.
  • Set values provide native methods like add, delete and clear.
  • String values provide native methods like concat, repeat, trim, etc.

This saves you from constantly re-writing the same state management logic, so you can keep your components focused on behavior and presentation.

For example, here's the classic state management "counter" example:

import { NumberValue } from 'react-values'

const Counter = () => (
  <NumberValue defaultValue={0}>
    {({ value, increment, decrement }) => (
      <button onClick={() => increment()}>+1</button>
      <span>{value}</span>
      <button onClick={() => decrement()}>-1</button>
    )}
  </NumberValue>
)

Of going further, here's a full fledged <Toggle> (respecting value/defaultValue and providing onChange) implemented in just a few lines of code using a <BooleanValue>:

import { BooleanValue } from 'react-values'

const Toggle = ({ value, defaultValue, onChange }) => (
  <BooleanValue value={value} defaultValue={defaultValue} onChange={onChange}>
    {({ value: on, toggle }) => (
      <Track on={on} onClick={toggle}>
        <Thumb on={on} />
      </Track>
    )}
  </BooleanValue>
)

const Track = styled.div`
  position: relative;
  height: 25px;
  width: 50px;
  background-color: ${props => (props.on ? 'lightgreen' : 'lightgray')};
  border-radius: 50px;
`

const Thumb = styled.div`
  position: absolute;
  left: ${props => (props.on ? '25px' : '0')};
  height: 25px;
  width: 25px;
  background-color: white;
  border-radius: 50px;
`

But you can go further, because react-values can "connect" a single value across multiple components. This is helpful any time you need a "global" piece of state in your app, without wanting to add tons of complexity.

For example, using the <Toggle> from above, here's a modal you can open and close from anywhere in your app:

import { createBooleanValue } from 'react-values'
import { Modal, Toggle } from './ui'

const ModalValue = createBooleanValue(false)

const App = () => (
  <div class="app">
    <div class="sidebar">
      <ModalValue>
        {({ value, set }) => (
          <Toggle value={value} onChange={set} />
        )}
      </ModalValue>
    </div>
    <div class="content">
      <ModalValue>
        {({ value: opened }) => (
          opened && <Modal />
        )}
      </ModalValue>
    </div>
  <div>
)

The primitives react-values gives you seem simple at first, but they can be composed together to create complex behaviors that are still easy to reason about, in just a few lines of code.


Why?

While building an app with React, you end up building a lot of stateful components in the process. Whether at the UI kit level for things like toggles, tooltips, checkbox groups, dropdown, etc. Or at the app level for modals, popovers, sorting, filtering, etc.

In the process, you end up re-implementing run of the mill state handling logic all over the place—whether with this.setState or by adopting some "state management framework" and writing the same boilerplate over and over again. And for your components to be nicely reusable across your application you augment them to handle both "controlled" and "uncontrolled" use cases using value or defaultValue. And to make things a bit more manageable, you re-invent common transforms like open, close, toggle, increment, decrement, etc. in lots of different components. And if you're working with a team, you end up doing all of this in slightly different ways throughout your codebase.

In the end, you're now maintaing a lot more logic than necessary, duplicated in many different places in slightly different ways. It gets harder and harder to understand your app's data flow. All while your app's bundle size grows.

react-values solves all of that with a few principles...


Principles

  1. Leverage render props. It uses a render-prop-based API, exposing its state and a handful of convenient transform functions to you with the flexible function-as-children pattern.

  2. Follow React's conventions. Its components follow React's own naming conventions, using familiar concepts like value/defaultValue. This makes it extremely easy to slot into existing codebases or frameworks.

  3. Follow JavaScript's conventions. It exposes JavaScript's familiar, built-in methods like setDate/setHours, push/pop, filter, concat, etc. to avoid reinventing the wheel and forcing you to constantly read documentation.

  4. Be extremely lightweight. It's extremely lightweight (and tree-shakeable), with most components weighing just a few hundred bytes, so you can even import it from public-facing component libraries.

  5. Prioritize convenience. It's designed to provide convenient functions like increment, toggle, and smarter ones like incrementDate, decrementMonth, so you can build complex interactions in just a few lines of code.


Examples

To get a sense for how you might use react-values, check out a few of the examples:

  • Basic Toggle — using a Boolean to create a simple toggle component.
  • Reusable Toggle — showing how you might turn that toggle into a controlled component in your own UI kit.
  • Counter — a simple counter using a Number and its convenience transforms.
  • Connected Counters — two counters that are connected together, sharing a single value.
  • Time Picker — a more complex time picker component, using Date and its convenience transforms.
  • Filtering — a basic String value used for filtering a list.
  • Checkbox Set — using a Set to keep track of a checkbox group.
  • Simple Tooltip — a simplistic tooltip implemented as a Boolean.
  • Simple Modal — a simplistic modal implemented as a Boolean.
  • Connected Modal — a modal whose opened/closed state is controllable from other components.

If you have an idea for an example that shows a common use case, pull request it!


Documentation

If you're using react-values for the first time, check out the Getting Started guide to familiarize yourself with how it works. Once you've done that, you'll probably want to check out the full API Reference.

If even that's not enough, you can always read the source itself.

There are also translations of the documentation into other languages:

If you're maintaining a translation, feel free to pull request it here!


Contributing!

All contributions are super welcome! Check out the Contributing instructions for more info!

react-values is MIT-licensed.

More Repositories

1

slate

A completely customizable framework for building rich text editors. (Currently in beta.)
TypeScript
28,970
star
2

superstruct

A simple and composable way to validate data in JavaScript (and TypeScript).
TypeScript
6,772
star
3

permit

An unopinionated authentication library for building Node.js APIs.
JavaScript
1,683
star
4

awesome-heroku

A curated list of helpful Heroku resources.
291
star
5

slate-plugins

A set of my personal Slate editor plugins, in a monorepo.
JavaScript
232
star
6

to-case

Simple case detection and conversion for strings.
JavaScript
122
star
7

minify

Simple, clean API for minifying Javascript, HTML or CSS.
JavaScript
112
star
8

hpmor

A set of covers for "Harry Potter and the Methods of Rationality".
112
star
9

css-color-function

A parser and converter for Tab Atkins's proposed color function in CSS.
JavaScript
91
star
10

is

Simple type checking.
JavaScript
77
star
11

router

A nice client-side router.
JavaScript
71
star
12

bump

Easily bump the version of all the different package.json equivalents.
JavaScript
65
star
13

heroku-logger

A dead simple logger, designed to be perfect for Heroku apps.
JavaScript
59
star
14

is-empty

Check whether a value is empty.
JavaScript
47
star
15

browser-logger

A dead simple logger, designed to be perfect for the browser.
JavaScript
44
star
16

download-github-repo

Download and extract a GitHub repository from node.
JavaScript
42
star
17

void

A toolkit for making generative art.
TypeScript
42
star
18

pg-sql-helpers

A set helpers for writing dynamic SQL queries with `pg-sql` in Javascript.
JavaScript
38
star
19

to-camel-case

Convert a string to a camel case.
JavaScript
36
star
20

rework-pure-css

Spiritual successor:
JavaScript
33
star
21

to-snake-case

Convert a string to a snake case.
JavaScript
26
star
22

history

A nicer wrapper around the browser's History API. Push, replace, back, forward, etc.
JavaScript
25
star
23

makefile-help

An easy way to add a `make help` target to your Makefiles.
Makefile
24
star
24

slate-drop-or-paste-images

Moved! This package has moved to ianstormtaylor/slate-plugins...
24
star
25

rework-color-function

Implements Tab Atkins's proposed color function in CSS.
CSS
22
star
26

slate-auto-replace

Moved! This package has moved to ianstormtaylor/slate-plugins...
22
star
27

trigger-event

Programmatically trigger a DOM event. Useful for unit testing mostly.
JavaScript
21
star
28

component-size

A component command to list the sizes of all your component's dependencies.
JavaScript
18
star
29

to-title-case

Convert a string to a title case.
JavaScript
17
star
30

component-update

A component command plugin to update out of date dependencies.
JavaScript
16
star
31

to-no-case

Remove an existing case from a string.
JavaScript
16
star
32

reset

An opinionated CSS reset for web *apps*.
CSS
15
star
33

css

Simple CSS manipulation.
JavaScript
15
star
34

component-outdated

A component command plugin to list outdated dependencies.
JavaScript
14
star
35

read-file-stdin

Read from a file, falling back to stdin.
JavaScript
14
star
36

create-event

Create an event object cross browser. Useful for unit testing mostly.
JavaScript
13
star
37

correct-email

Correct common misspellings in an email address, based on Kicksend's Mailcheck library.
JavaScript
13
star
38

backbone-inheritance

(I no longer use Backbone, but feel free to check this plugin out. The code is pretty straightforward.) A Backbone.js mixin that lets Views inherit properties from their parents.
JavaScript
12
star
39

to-capital-case

Convert a string to a capital case.
JavaScript
11
star
40

to-slug-case

Convert a string to a slug case.
JavaScript
11
star
41

jquery-state

A jQuery plugin that makes setting states in the DOM easy and accessible.
JavaScript
11
star
42

animate

Easily apply animate.css animations to elements via Javascript.
CSS
10
star
43

slate-paste-linkify

Moved! This package has moved to ianstormtaylor/slate-plugins...
10
star
44

backbone-state

(I no longer use Backbone, but feel free to check this plugin out. The code is pretty straightforward.) A Backbone.js mixin that adds states to Views.
JavaScript
9
star
45

slate-soft-break

Moved! This package has moved to ianstormtaylor/slate-plugins...
8
star
46

title-case-minors

A list of the minor words that shouldn't be capitalized in a title case string.
JavaScript
8
star
47

closest-match

Find the closest match for a string from an array of matches, using string distance.
JavaScript
7
star
48

loading

A simple way to toggle loading state.
JavaScript
7
star
49

to-sentence-case

Convert a string to a sentence case.
JavaScript
6
star
50

makefile-assert

An easy way to assert that an environment variable is defined in your Makefiles.
Makefile
6
star
51

mailto

Programmatically open the user's email client.
JavaScript
6
star
52

assert-dir-equal

Assert that the contents of two directories are equal.
JavaScript
6
star
53

write-file-stdout

Write to a file, falling back to stdout.
JavaScript
6
star
54

slate-auto-replace-text

Deprecated! Use ianstormtaylor/slate-auto-replace instead...
6
star
55

to-space-case

Convert a string to a space case.
JavaScript
5
star
56

to-dot-case

Convert a string to a dot case.
JavaScript
5
star
57

parallel

A simple API for running async functions in parallel.
JavaScript
4
star
58

rework-font-variant

Implements the font-variant-* properties for browsers that don't yet support them.
JavaScript
4
star
59

to-constant-case

Convert a string to a constant case.
JavaScript
4
star
60

email

Parse an email address into its components, based on component/url.
JavaScript
4
star
61

parent

Get the parent of an element.
JavaScript
3
star
62

get

Get a property from a model or object.
JavaScript
3
star
63

to-pascal-case

Convert a string to pascal case.
JavaScript
3
star
64

classes

Quickly mixin class helper methods to a view.
JavaScript
3
star
65

bind

A clear API for function binding helpers.
JavaScript
3
star
66

map

Map an array or object.
JavaScript
3
star
67

matchuppps

My 10K Apart 2010 entry that won Best Design
JavaScript
3
star
68

slate-collapse-on-escape

Moved! This package has moved to ianstormtaylor/slate-plugins...
3
star
69

backbone-getset

(I no longer use Backbone, but feel free to check this plugin out. The code is pretty straightforward.) A Backbone.js mixin that adds a getter and setter to Backbone Views.
JavaScript
2
star
70

typekit

Load a Typekit kit asynchronously, automatically handling FOUT.
JavaScript
2
star
71

backbone-events

(I no longer use Backbone, but feel free to check this plugin out. The code is pretty straightforward.) A Backbone.js mixin that lets you define all your events in one place.
JavaScript
2
star
72

reduce

Reduce an array or object.
JavaScript
1
star
73

changesets-logo

A logo for Changesets.
1
star
74

pick

Pick keys from an object, returning a clone.
JavaScript
1
star
75

callback

Sugar for couthly calling functions back.
JavaScript
1
star
76

graph

WIP, naming ideas much appreciated :)
JavaScript
1
star
77

redraw

Force a redraw on an element.
JavaScript
1
star
78

on-load

Callback when the document has loaded.
JavaScript
1
star
79

set

Set a property on a model or object.
JavaScript
1
star
80

case

Moved to https://github.com/ianstormtaylor/to-case
JavaScript
1
star
81

slate-auto-replace-block

Deprecated! Use ianstormtaylor/slate-auto-replace instead...
1
star