react-input-component
v0.2.0
Published
react-input-component
Downloads
23
Maintainers
Readme
react-input-component
🚀 A better alternative to react built-in input components
Motivations
- Before use built-in react inputs, you may need to know what the hell are controlled and uncontrolled inputs
- Controlled input has a bug
- Controlled input is slow
- Uncontrolled input is not powerful
So I created this module to avoid the problems above.
Installation
yarn add react-input-component
Usages
Just like built-in input components, but no defaultValue
or defaultChecked
prop.
Example
import React from 'react';
import { Input } from 'react-input-component';
export default () =>
<Input value="feel free to type here..." />
Components
- Input
- TextArea
- Select
Notes
- All styles are the same with react built-in inputs
- All react built-in inputs' props are supported, except
defaultValue
anddefaultChecked
- To get the DOM, use
findDOMNode(input)
orinput.dom
. (Thisinput
refs to anInput
instance, like<Input ref="input" />
) - Form data (value or checked) would be handled by the DOM itself.
- Form data could also be changed by passing new
value
prop to component.
Caveat
If the new value
prop is equal to the prev value
prop, form data would not be updated, even if form data is not equal to the value
prop.
import React, { Component } from 'react';
import { render, findDOMNode } from 'react-dom';
import { Input } from 'react-input-component';
class Bad extends Component {
state = { value: 'a' };
componentDidMount() {
findDOMNode(this).value = 'b'; // Simulate user typing
// Try to reset `value` to "a", but failed
// Because the new `value` prop is equal to the prev `value` prop
this.setState({ value: 'a' }); // => BAD
}
render() {
return (<Input {...this.state} />);
}
}
render(<Bad />, document.getElementById('root'));
To resolve this problem, you could change the DOM value directly, or add a special updateKey
prop.
updateKey
helps Input component to decide to update. If updateKey
changes, form data changes.
import React, { Component } from 'react';
import { render, findDOMNode } from 'react-dom';
import { Input } from 'react-input-component';
class Good extends Component {
state = { value: 'a' };
componentDidMount() {
findDOMNode(this).value = 'b'; // Simulate user typing
// Try to reset `value` to "a"
// Adding a new `updateKey` to force upate
this.setState({ value: 'a', updateKey: Math.random() }); // => GOOD
}
render() {
return (<Input {...this.state} />);
}
}
render(<Good />, document.getElementById('root'));
License
MIT © Cap32