Home:ALL Converter>Mask card number input in React

Mask card number input in React

Ask Time:2015-06-06T00:21:36         Author:Eugene Matveyev

Json Formatter

I'm learning React and want to make an input with two constraints:

  • 16 numbers,
  • put a space after every fourth.
import React, { Component } from 'react';

export default class CardNumberInput extends Component {
  constructor() {
    super();
    this.state = { value: '' };
  }

  handleChange(event) {
    React.findDOMNode(this.refs.cardInput).mask("0000 0000 0000 0000");
    this.setState({ value: event.target.value });
  }

  render() {
    let value = this.state.value;

    return (
      <div>
        <label htmlFor="cardInput">Card Number: </label>
        <input ref="cardInput" id="cardInput" onChange={this.handleChange} type="number" value={value} />
      </div>
    );
  }
}

I don't know whether I'm doing it right (use refs), because console.log(React.findDOMNode(this.refs.cardInput)) returns null o_O

p.s. .mask is from http://igorescobar.github.io/jQuery-Mask-Plugin/

Author:Eugene Matveyev,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/30671302/mask-card-number-input-in-react
FriC :

The mask function must be applied to a jquery object, not a plain dom element, and you also need to put this line in componentDidMount.\n\ncomponentDidMount: function () {\n var $input_elem = $(React.findDOMNode(this.refs.cardInput));\n // now you have a jquery object\n $input_elem.mask(\"0000 0000 0000 0000\", callback_options);\n}\n\n\nHowever, the callback options for this plugin still need to be integrated with the react lifecycle methods. First try making it an uncontrolled component (use defaultValue instead of value) and check that it works.",
2015-06-06T05:35:06
Taysky :

You are rendering this.state.value every time you make a change, which is overwriting the mask.\n\nThe mask is being overwritten by the render.\n\nYou need to move the mask() to render so that it masks the value before it writes to the dom.\n\n\n Computed data: Don't worry about precomputing values based on state — it's easier to ensure that your UI is consistent if you do all computation within render(). For example, if you have an array of list items in state and you want to render the count as a string, simply render this.state.listItems.length + ' list items' in your render() method rather than storing it on state.\n https://facebook.github.io/react/docs/interactivity-and-dynamic-uis.html\n",
2015-06-05T20:00:08
yy