⚡️ Utility function to handle input changes in React.
MIT License
Utility function to handle input changes in React based on React's handling multiple input docs.
<input />
s, <textarea />
and <select />
elements.<select multiple />
.yarn add react-input-handler
or
npm install react-input-handler --save
Two things needs to be done to use react-input-handler:
onChange
events.import React from 'react'
import ReactInputHandler from 'react-input-handler'
export default class Form extends React.Component {
constructor(props) {
super(props)
this.state = {}
this.handleChange = ReactInputHandler.bind(this)
this.handleSubmit = this.handleSubmit.bind(this)
}
render() {
return (
<form onSubmit={this.handleSubmit}>
<label>Fullname:</label>
<input type="text" name="user.fullname" onChange={this.handleChange} />
<label>Biography:</label>
<textarea type="text" name="user.bio" onChange={this.handleChange} />
<label> Are you a developer?</label>
<input type="checkbox" name="user.developer" value="yes" onChange={this.handleChange} />
<button type="submit">Submit</button>
</form>
)
}
handleSubmit(event) {
event.preventDefault()
console.log(this.state)
// Output: { user: { fullanme: "string", bio: "string", developer: true|false } }
}
}
React-input-handler is a single function which accept two argument: an event and a optional callback function that will be passed to the setState
method.
The objective is simple: handle input changes and persist them into the component's state.
By default, react-input-handler handles checkbox as boolean value. Sometimes, we may want two or more checkboxes to be handled as an array sharing the same name
attribute. To achieve this we have to suffix the name
attribute with []
. For example:
Before:
<input type="checkbox" name="one" value="1" onChange={this.inputHandler} checked />
<input type="checkbox" name="two" value="2" onChange={this.inputHandler} />
<input type="checkbox" name="three" value="3" onChange={this.inputHandler} checked />
// state: { one: true, two: false, three: true }
After:
<input type="checkbox" name="numbers[]" value="1" onChange={this.inputHandler} checked />
<input type="checkbox" name="numbers[]" value="2" onChange={this.inputHandler} />
<input type="checkbox" name="numbers[]" value="3" onChange={this.inputHandler} checked />
// state: { numbers: ["1", "3"] }
yarn
or npm install
.yarn test
- to run all tests.yarn test -- --watch
to run all tests in watch mode.npm version x.x.x -m 'Version %s.'
.npm publish
.git push origin --tags
.Made with ❤️ by Rubens Mariuzzo.