nosir / cleave.js

Format input text content when you are typing...
http://nosir.github.io/cleave.js
Apache License 2.0
17.96k stars 1.62k forks source link

React with Redux double backspace #129

Closed Jafferwaffer closed 7 years ago

Jafferwaffer commented 8 years ago

The credit card formatter incorrectly removes one more character than it is supposed to. Eg:

init value = 1234*| (* being delimiter)
press backspace
returned value = 12|

The issue seems to occur using the React Cleave component with Redux. I am storing the rawValue in the state, { creditCardNumber: rawValue } . The value is set to state.creditCardNumber.

I was able to reproduce: https://jsfiddle.net/rL8onrdx/

The onInput(newValue) function is being called multiple times, as the owner.properties.initValue is not being updated after the first onInput runs and so in the componentWillRecieveProps function the

newValue !== owner.properties.initValue

Where the newValue is correctly 123 but the initValue is still 1234 After the second onInput runs the result is as shown above, however, the state's value is correctly 123

harjup commented 8 years ago

+1, I am also experiencing this issue.

This is gross, but seems to make the input field work: https://jsfiddle.net/44g248db/

var state = { creditCardNumber: '' };

var renderApp = function(props) {
  ReactDOM.render(<Cleave placeholder="Enter credit card number"
          options={{creditCard: true}}
          onInput={onInput}
          onChange={onChange}
          value={props.creditCardNumber}
    />, document.getElementById('content'));
}

var onInput = function(e) {
    state.creditCardNumber = e.target.value;
}

var onChange = function() {
    renderApp(state);
}

renderApp(state);
nosir commented 7 years ago

Basically, there is no need to bind state to value attribute for Cleave component.

The way it works: input value is controlled by Cleave component internally, when the data is changed, onChange event will be triggered. Then externally, you update the state with value or rawValue as you want.

I believe here contentA is what you want: https://jsfiddle.net/nosir/Lz9mc17h/

Also contentB in above link is the only case you might use value: to set a default value for the component.

Jafferwaffer commented 7 years ago

Thank you for the response @nosir, I'll let you know how this works out for me when I get back to it.

nosir commented 7 years ago

Okay, sorry for the long delay lol

nosir commented 7 years ago

More explanation if you interested: https://github.com/nosir/cleave.js/blob/master/doc/reactjs-component-usage.md#how-to-update-raw-value

Jafferwaffer commented 7 years ago

Thank you nosir that worked well for me, the only thing I would say is that it would be nice to have a way of setting the initial raw value without firing the onChange.

This has resolved my original issue, so feel free to close. Ty

nosir commented 7 years ago

@Jafferwaffer 👍