Search code examples
jqueryreactjsmaskedinput

ReactJS: mask input


I am trying to create an masked input component using ReactJS. Following Mask card number input in React i get error: Object doesn't support property or method 'mask'.

I did have to make some changes because it seems the post may be a bit outdated, so maybe there are other things i need to change that i'm not aware of.

This is my component:

import React, { Component } from 'react';
import ReactDOM from 'react-dom'
import $ from 'jquery';

export default class MaskedInput extends Component {
    constructor(props) {
        super(props); 
    }

    componentDidMount() {
        let $input_elem = $(ReactDOM.findDOMNode(this.maskedInput))[0];
        console.log($input_elem);
//      // now you have a jquery object
        $input_elem.mask("0000 0000 0000 0000");
    }

    render() {
        return <input ref={(input)=> {this.maskedInput = input; }} id="cardInput" onChange={this.props.handleChange} type="number" value="" />
    }
}

So, i guess i was missing the jquery-mask-plugin, which i installed with

npm install --save jquery-mask-plugin

So I changed this line:

import $ from 'jquery-mask-plugin';

But, now i get an error on this line:

let $input_elem = $(ReactDOM.findDOMNode(this.maskedInput))[0];

error: Function expected

I tried removing the index at the end, but that didn't help.


Solution

  • I wanted to create my own component to avoid installing third-party libraries, but since i would have to install jquery for this solution, might as well install react-maskedinput which already solves the problem and it is a better choice for React than jquery.