Dan With The Plan
Dan With The Plan

Reputation: 135

Conditional Phone Mask numbers in ReactJS as an if statement or function

I am trying to have my input be shown as the US phone number format until I reach the 10th input. Once I reach the 11th input I would like to have it lose the mask format.

attached is my ReactJS code:

import React, { Component } from 'react';
import NumberFormat from 'react-number-format';

class App extends Component {
  state ={
  userInput: ''
}
phoneNumberFormatHandler =(values, event)=>{
console.log("values are " + values);
console.log("events are " + event);
}

  inputChangedHandler = (values, event) => { 
   this.setState({userInput: values});
  console.log(values);
  console.log(event);
  console.log(this.formatPhoneNumber(values.value));
  }
  render() {
    return (
      <div className="App">
                <NumberFormat
            // format="(###) ###-####"
            mask=""
            name="phoneNumberInput"
            placeholder="Phone Number Here"
            onValueChange={this.inputChangedHandler}
            value={this.state.userInput.value}
          />
<p><strong>Value: </strong>+1{this.state.userInput.value}</p>
        </div>
    );
  }
}

export default App;

Upvotes: 1

Views: 2007

Answers (1)

saharbit
saharbit

Reputation: 66

this.state.userInput.length <= 10 ? mask=this.formatPhoneNumber : mask=this.state.userInput

Set a conditional to determine whether the input is above 10 characters, and if it is then don't format it.

Upvotes: 1

Related Questions