react-draft-value
TypeScript icon, indicating that this package has built-in type declarations

0.0.0 • Public • Published

react-draft-value

A HOC that provides a temporary (or draft) state to child components.

The component takes a value prop and an onChange prop, and treats children as a render prop.

The render prop function receives an argument with value and onChange properties (and in case you need it, a nonDraftValue property that has the original unmodified value prop).

Within the render prop function, calling the onChange handler will update the draft value.

If the component's value prop changes, it will overwrite the draft value as well.

Whenever the onChange handler in the render prop function is called, the onChange handler on the component is called with the draft value, and you can decide whether or not to do anything with it.

Suggested Use Cases:

  • throttling setState calls
  • performing localized form input validation
  • showcasing controlled components without manual state management

Example usage

This example shows a (controlled) JSON input text area, that receives and emits JSON JavaScript objects. It only triggers onChange events when the text area contains valid parseable JSON. The text color changes to red while the draft value is in this unparseable state.

import TextareaAutosize from "react-textarea-autosize";

export const JsonInput: React.SFC<IFormtronControl> = ({
  value,
  onChange
}) => (
  <DraftValue
    value={JSON.stringify(value, null, 2)}
    onChange={draft => {
      try { onChange(JSON.parse(draft)) } catch (err) {}
    }}
  >
    {({ value, onChange, nonDraftValue }) => (
      <TextareaAutosize
        style={{ color: nonDraftValue === value ? undefined : "red" }}
        id={id}
        value={value}
        onChange={e => onChange(e.target.value)}
      />
    )}
  </DraftValue>
);

Readme

Keywords

none

Package Sidebar

Install

npm i react-draft-value

Weekly Downloads

0

Version

0.0.0

License

MIT

Unpacked Size

5.82 kB

Total Files

5

Last publish

Collaborators

  • wmhilton