Enter the card number in the "React" field

I am learning React and want to make input with two constraints:

  • 16 rooms,
  • enter 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 if I'm doing it right (use refs) because console.log (React.findDOMNode (this.refs.cardInput)) returns null o_O

ps.mask from http://igorescobar.github.io/jQuery-Mask-Plugin/

+3


source to share


2 answers


The mask function needs to be applied to a jquery object, not a simple dom element, and you need to put that line in componentDidMount as well.

componentDidMount: function () {
    var $input_elem = $(React.findDOMNode(this.refs.cardInput));
    // now you have a jquery object
    $input_elem.mask("0000 0000 0000 0000", callback_options);
}

      



However, the callback parameters for this plugin still need to be integrated with lifecycle reactants. Try making it an uncontrolled component first (use defaultValue instead of value) and make sure it works.

+3


source


You render this.state.value every time you make a change that overwrites the mask.

The mask is overwritten by the render.



You need to move the mask () to render so that it masks the value before writing to the dom.

Calculated data: Don't worry about pre-calculating values ​​based on state - it's easier to make sure your UI is consistent if you do all the calculations in render (). For example, if you have an array of list items in a state and you want to display the count as a string, just render this.state.listItems.length + "list items" in your render () method, rather than store it in the state, https: //facebook.github.io/react/docs/interactivity-and-dynamic-uis.html

+1


source







All Articles