Dan With The Plan
Dan With The Plan

Reputation: 135

React manipulating NumberFormat format to work conditional

I am having trouble with manipulating the format from React's NumberFormat.

I need it to turn out as format="(###) ###-####" if the user inputs 10 numbers, but when the user ads the 11th number, the format must be discarded but the numbers still shown.

This is what I've tried so far:

import React, { Component } from "react";
import NumberFormat from "react-number-format";
import PhoneInputHandler from "./PhoneInputHandler/PhoneInputHandler";
class App extends Component {
  state = {
    userInput: ""
  };
  phoneNumberFormatHandler = values => {
    console.log(values);
    //  this.state.userInput.length <= 10 ? this.format="(###) ###-####" : this.format=this.state.userInput.values
  };
  render() {
    return (
      <div className="App">
        {/* <input type="number"
            name="phoneNumberInput"
            placeholder='Phone Number Here'
            onChange={this.inputChangedHandler}
            value={this.state.userInput}/>
            format="(###) ###-####"
            <p id='PhoneOutput'><strong>Value: </strong>+1{this.state.numAsString}</p>
             */}
        <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: 3

Views: 14543

Answers (1)

Tholle
Tholle

Reputation: 112777

You could add another # at the end of your format string, and check if your userInput has a length less than 11 and only give NumberFormat a format prop if that is the case.

Example

class App extends Component {
  state = {
    userInput: ""
  };

  inputChangedHandler = values => {
    this.setState({ userInput: values.value });
  };

  render() {
    const { userInput } = this.state;

    return (
      <div className="App">
        <NumberFormat
          format={userInput.toString().length < 11 ? "(###) ###-#####" : undefined}
          name="phoneNumberInput"
          placeholder="Phone Number Here"
          onValueChange={this.inputChangedHandler}
          value={userInput}
        />
        <p>
          <strong>Value: </strong>+1{userInput}
        </p>
      </div>
    );
  }
}

Upvotes: 3

Related Questions