Kal
Kal

Reputation: 1774

Reactjs - Call custom function to replace characters as the user types

I have a phone number input in my React App. I want to replace non numeric characters that the user types to spaces. I have written the following regex function to do that:

utils.js

/**
 * Phone Number - Only allow numbers
 */
export const phoneReplacer = el => {
  let elem = new d(el)
  let regex = /[^0-9]/i

  elem.on('keyup', e => {
    let value = e.currentTarget.value
    elem.setValue(value.replace(regex, ''))
  })
}

How to hook this up to my input component which is below:

import React from 'react'
import PropTypes from 'prop-types'
import TextInput from '../others/input/text'
import phoneReplacer from '../../../utils'

const PhoneInput = ({ value, change }) => (
  <div className="edit_phone_div">
    <TextInput
      type="text"
      placeholder="Phone Number"
      value={value}
      valueChange={e => change('phone', e)}
    />
  </div>
)

Upvotes: 1

Views: 2439

Answers (1)

Jimmay
Jimmay

Reputation: 722

The best way to attack this problem is with controlled components.

You can use your regex in multiple ways, however the way I'd prefer to use it is in the following way:

import React from "react";
import ReactDom from "react-dom";

class TelInput extends React.Component {
  state = { value: "" };

  telChange = e => {
    let text = e.target.value;

    text = text.replace(/[\D]+/g, " ");

    this.setState({ value: text });
  };

  render() {
    return (
      <input
        type="tel"
        placeholder="Phone Number"
        value={this.state.value}
        onChange={this.telChange}
      />
    );
  }
}

const rootElement = document.getElementById("root");
ReactDom.render(<TelInput />, rootElement);

If you still want to use your utility function, you could still call it from inside telChange (in this case) which can perform the logic for you, what I had text = text.replace(/[\D]+/g, " "); do in this instance. That way you could replace that line with:

text = phoneReplacer(text) // From utils.js

and you'll get the best of both worlds.

In general, you don't want to try to manipulate the DOM directly like your utility function is trying to do, you can leverage react itself to build the capabilities you're looking for.

Cheers! Jimmy

Upvotes: 1

Related Questions