react-draft-value
v0.0.0
Published
A HOC that provides a temporary (or draft) state to child components.
Downloads
3
Readme
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>
);