• Stars
    star
    194
  • Rank 200,219 (Top 4 %)
  • Language
    TypeScript
  • License
    MIT License
  • Created over 9 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

Wrap a controlled react component, to allow specific prop/handler pairs to be uncontrolled

uncontrollable

Wrap a controlled react component, to allow specific prop/handler pairs to be omitted by Component consumers. Uncontrollable allows you to write React components, with minimal state, and then wrap them in a component that will manage state for prop/handlers if they are excluded.

Install

npm i -S uncontrollable

Usage

If you are a bit unsure on the why of this module read the next section first. If you just want to see some real-world examples, check out React Widgets which makes heavy use of this strategy.

import { uncontrollable } from 'uncontrollable';

API

useUncontrolledProp(value, defaultValue, onChange) => [value, onChange]

A React hook that can be used in place of the above Higher order Component. It returns a complete set of props which are safe to spread through to a child element.

import { useUncontrolledProp } from 'uncontrollable';

const UncontrolledCombobox = ({ value, defaultValue, onChange }) => {
  // filters out defaultValue, defaultOpen and returns controlled
  // versions of onChange, and onToggle.
  const [controlledValue, onControlledChange] = useUncontrolledProp(
    value,
    defaultValue,
    onChange
  );

  return <Checkbox {...controlledProps} />;
};

useUncontrolled(props, propsHandlerHash) => controlledProps

A React hook that can be used in place of the above Higher order Component. It returns a complete set of props which are safe to spread through to a child element.

import { useUncontrolled } from 'uncontrollable';

const UncontrolledCombobox = (props) => {
  // filters out defaultValue, defaultOpen and returns controlled
  // versions of onChange, and onToggle.
  const controlledProps = useUncontrolled(props, {
    value: 'onChange',
    open: 'onToggle',
  });

  return <Checkbox {...controlledProps} />;
};

Use Case

One of the strengths of React is its extensibility model, enabled by a common practice of pushing component state as high up the tree as possible. While great for enabling extremely flexible and easy to reason about components, this can produce a lot of boilerplate to wire components up with every use. For simple components (like an input) this is usually a matter of tying the input value prop to a parent state property via its onChange handler. Here is an extremely common pattern:

  render() {
    return (
      <input type='text'
        value={this.state.value}
        onChange={ e => this.setState({ value: e.target.value })}
      />
    )
  }

This pattern moves the responsibility of managing the value from the input to its parent and mimics "two-way" databinding. Sometimes, however, there is no need for the parent to manage the input's state directly. In that case, all we want to do is set the initial value of the input and let the input manage it from then on. React deals with this through "uncontrolled" inputs, where if you don't indicate that you want to control the state of the input externally via a value prop it will just do the book-keeping for you.

This is a great pattern which we can make use of in our own Components. It is often best to build each component to be as stateless as possible, assuming that the parent will want to control everything that makes sense. Take a simple Dropdown component as an example

class SimpleDropdown extends React.Component {
  static propTypes = {
    value: React.PropTypes.string,
    onChange: React.PropTypes.func,
    open: React.PropTypes.bool,
    onToggle: React.PropTypes.func,
  };

  render() {
    return (
      <div>
        <input
          value={this.props.value}
          onChange={(e) => this.props.onChange(e.target.value)}
        />
        <button onClick={(e) => this.props.onToggle(!this.props.open)}>
          open
        </button>
        {this.props.open && (
          <ul className="open">
            <li>option 1</li>
            <li>option 2</li>
          </ul>
        )}
      </div>
    );
  }
}

Notice how we don't track any state in our simple dropdown? This is great because a consumer of our module will have the all the flexibility to decide what the behavior of the dropdown should be. Also notice our public API (propTypes), it consists of common pattern: a property we want set (value, open), and a set of handlers that indicate when we want them set (onChange, onToggle). It is up to the parent component to change the value and open props in response to the handlers.

While this pattern offers an excellent amount of flexibility to consumers, it also requires them to write a bunch of boilerplate code that probably won't change much from use to use. In all likelihood they will always want to set open in response to onToggle, and only in rare cases will want to override that behavior. This is where the controlled/uncontrolled pattern comes in.

We want to just handle the open/onToggle case ourselves if the consumer doesn't provide a open prop (indicating that they want to control it). Rather than complicating our dropdown component with all that logic, obscuring the business logic of our dropdown, we can add it later, by taking our dropdown and wrapping it inside another component that handles that for us.

uncontrollable allows you separate out the logic necessary to create controlled/uncontrolled inputs letting you focus on creating a completely controlled input and wrapping it later. This tends to be a lot simpler to reason about as well.

  import { uncontrollable } from 'uncontrollable';

  const UncontrollableDropdown = uncontrollable(SimpleDropdown, {
    value: 'onChange',
    open: 'onToggle'
  })

  <UncontrollableDropdown
    value={this.state.val} // we can still control these props if we want
    onChange={val => this.setState({ val })}
    defaultOpen={true} /> // or just let the UncontrollableDropdown handle it
                          // and we just set an initial value (or leave it out completely)!

Now we don't need to worry about the open onToggle! The returned component will track open for us by assuming that it should just set open to whatever onToggle returns. If we do want to worry about it we can just provide open and onToggle props and the uncontrolled input will just pass them through.

The above is a contrived example but it allows you to wrap even more complex Components, giving you a lot of flexibility in the API you can offer a consumer of your Component. For every pair of prop/handlers you also get a defaultProp of the form "default[PropName]" so value -> defaultValue, and open -> defaultOpen, etc. React Widgets makes heavy use of this strategy, you can see it in action here: https://github.com/jquense/react-widgets/blob/5d1b530cb094cdc72f577fe01abe4a02dd265400/src/Multiselect.jsx#L521

More Repositories

1

yup

Dead simple Object schema validation
TypeScript
21,194
star
2

react-big-calendar

gcal/outlook like calendar component
JavaScript
7,846
star
3

react-widgets

Polished, feature rich, accessible form inputs built with React
TypeScript
2,318
star
4

react-formal

Sophisticated HTML form management for React
TypeScript
528
star
5

teaspoon

A jQuery like API for testing React elements and rendered components.
JavaScript
388
star
6

react-dom-lite

Tiny dom implementation using react-reconciler
JavaScript
246
star
7

react-bootstrap-modal

React port of jschr's better bootstrap modals
JavaScript
89
star
8

jarle

Just Another React Live Editor
JavaScript
65
star
9

topeka

Idiomatic, "two-way" bindings, in React.
TypeScript
56
star
10

date-math

simple date math module
JavaScript
53
star
11

bill

css selector engine for React elements and components
JavaScript
53
star
12

react-layer

Simple abstraction for creating and managing new render trees
JavaScript
44
star
13

react-input-message

A small, completely unopinionated way, to display messages next to inputs based on events. Helpful for displaying input validation messages
JavaScript
42
star
14

docusaurus-theme-tailwind

TailwindCSS based Docusaurus theme
TypeScript
29
star
15

webpack-atoms

Small atomic bits for crafting webpack configs
TypeScript
25
star
16

react-component-metadata

JavaScript
21
star
17

expr

tiny util for getting and setting deep object props safely
JavaScript
20
star
18

babel-plugin-jsx-fragment

jsx syntatic sugar for React's `createFragment()`
JavaScript
16
star
19

mp4-info-parser

JavaScript
12
star
20

sass-tailwind-functions

Sass plugin implementing TailwindCSS functions
JavaScript
11
star
21

react-dialog

programtic replacements for Alert and Confirm in React
JavaScript
9
star
22

babel-preset-jason

JavaScript
9
star
23

node-stream-tokenizr

fluent streaming binary parser for working buffer chunks, strings, and byte words
JavaScript
7
star
24

react-formal-inputs

a react-widgets adaptor for react-formal
JavaScript
7
star
25

webpack-config-utils

experiments in webpack config building
JavaScript
7
star
26

babel-preset-env-modules

JavaScript
6
star
27

markdown-jsx-loader

JavaScript
6
star
28

component-metadata-loader

webpack loader to parse React component metadata from source code
JavaScript
5
star
29

mpeg-frame-parser

JavaScript
5
star
30

mini-storybook

no frills story book for components
JavaScript
5
star
31

ogg-info-parser

small streaming .ogg parser for Node.js
JavaScript
5
star
32

tiny-case

JavaScript
4
star
33

vorbis-info-parser

Small parser for Vorbis Bit streams
JavaScript
4
star
34

docpocalypse

TypeScript
4
star
35

vscode-hrx

Syntax Grammar for HRX files
JavaScript
4
star
36

css-module-loader

JavaScript
4
star
37

ID3v2-info-parser

ID3 tag version 2 streaming parser
JavaScript
4
star
38

chain-function

chain a bunch of functions
JavaScript
4
star
39

react-clonewithprops

Stand-alone React cloneWithProps util that works with multiple versions of React
JavaScript
3
star
40

flac-info-parser

JavaScript
3
star
41

node-audio-info

JavaScript
2
star
42

browser-test-pages

2
star
43

react-component-managers

utilities for composing functionality into react-components, alt-mixin
JavaScript
2
star
44

mtag

mp3 Tagging and Batch Altering Scripts
Python
2
star
45

ID3v1-info-parser

JavaScript
2
star
46

scoped-warning

Creates a scoped warning() error for tracking who is throwing what
JavaScript
2
star
47

tiny-set-immediate

Modern polyfill for set immediate
TypeScript
2
star
48

match-resource-repro

JavaScript
2
star
49

react-tackle-box

JavaScript
2
star
50

node-ktc

Pre-compiler for Kendo UI Core templates
JavaScript
2
star
51

asf-info-parser

JavaScript
2
star
52

StringUtils

Common string utilities
C#
1
star
53

style-convert-macro

Convert CSS strings to CSS object styles
JavaScript
1
star
54

babel-plugin-external-helpers

insert require for babel helpers
JavaScript
1
star
55

astonish

JavaScript
1
star
56

sound-bytes

JavaScript
1
star
57

oauthenticity

JavaScript
1
star
58

test-publish-actions

JavaScript
1
star
59

cobble

tiny object js object model for doing compositional inheritance
JavaScript
1
star
60

node-simple-chainable

A small node module for queuing a series of functions that follow from each other
JavaScript
1
star
61

svelte-combobox

Created with CodeSandbox
Svelte
1
star
62

kwik-e-mart

pub/sub and datastore
JavaScript
1
star
63

babel-plugin-globalize

Extract formatters and messages from source code
JavaScript
1
star
64

webpack-pitch-repro

JavaScript
1
star