Inputmask: React onChange event doesn't work with Inputmask
There’s the issue.
When attaching Inputmask to event inside of react component there is no way to know when
value has been changed.
React uses input event to implement its onChange, so now there is now way to listen input when Inputmask attached. Also it does not matter when i attaching event handler (before or after Inputmask), input event will never fire.
And yes, there is no other way to handle input changes if i want to sync value with component state.
There is an example of how does it behave: http://codepen.io/nicholasrq/pen/kkaEoL?editors=0010
UPD: I’ve added a button to enable/disable masking to ensure that native behaviour works when no mask attached.
Also code example:
class Input extends React.Component{
constructor(props){
super(props)
this.state = {
mask: true
}
this.onChange = this.onChange.bind(this)
this.toggleMask = this.toggleMask.bind(this)
}
render(){
// attaching onChange in react-way
// no luck
return (
<div>
<input onChange={this.onChange} ref="input" placeholder="input" type="text"/>
<button onClick={this.toggleMask}>{this.state.mask ? 'disable' : 'enable'}</button>
</div>
)
}
componentDidMount(){
// this callback will be invoked right after
// the component is completely rendered
// let's take reference to input
const input = this.refs.input
// now let's try to add native event
// handler BEFORE masking. not working
input.addEventListener('input', this.onChange, false)
// attaching inputmask
this.attachMask()
// also will not work
input.addEventListener('input', this.onChange, false)
}
componentDidUpdate(prevProps, prevState){
if(prevState.mask != this.state.mask){
if(this.state.mask){
this.attachMask()
} else {
this.mask.remove(this.refs.input)
}
}
}
attachMask(){
const mask = new Inputmask({ mask: '99.99.99' })
this.mask = mask.mask(this.refs.input)
}
onChange(e){
console.log(e.target.value)
}
toggleMask(){
this.setState({mask: !this.state.mask})
}
}
console.clear();
ReactDOM.render(<Input/>, document.querySelector('#wrapper'))
About this issue
- Original URL
- State: closed
- Created 8 years ago
- Reactions: 3
- Comments: 20 (9 by maintainers)
Commits related to this issue
- Make change event bubble #1377 — committed to RobinHerbots/Inputmask by RobinHerbots 7 years ago
@nicholasrq Did you manage to get this working somehow?
@nicholasrq , @an-kh ,
I made some modification in the vanilla dependencylib which could fix the problem in react. Can you have a try.
Also, I want to mention that
autoUnmaskproperty is not working anymore with React in IE 11. #1187@RobinHerbots
Yep, it invokes it’s own
SynteticEvent’s. In case ofonChangereact will handle nativeinputevent to correctly sync it’s own state with input value.You still can use my Pen as example if you’re going to debug this particular case http://codepen.io/nicholasrq/pen/kkaEoL?editors=0010
I believe that with growing popularity of React there is a reason to support it out of the box 😃