vijayaganth vijayaganth - 8 months ago 58
React JSX Question

How to make text box first value non editable in React js?

I need to make a text box field for coutry code generate. So I need to put first letter as a "+" symbol only. And then make it not editable field for that symbol.

_handlePhoneNumber(e) {
var curState = {};
var valueLength = e.target.value.length;
var currentValue = e.target.value;
console.log(currentValue);

curState[e.target.name] = this.mobileOnly(currentValue);
this.setState(curState);
}

<input type="tel" name="countryCode" value={this.state.countryCode} onChange={this._handlePhoneNumber.bind(this)} />

Answer Source

Define the initial value of this.state.countryCode as +:

this.state = {
   countryCode: '+'
}

Inside onChange function check the length of value entered by user and if length == 0 then do not update the state value. By this way user will not be able to remove the + sign, because we are not updating the state when length is equals to 0.

Like this:

_handlePhoneNumber(e) {
    if(e.target.value.length > 0){        //then only update the state value

        this.setState({
            [e.target.name]: this.mobileOnly(e.target.value)
        });

    }
}

Note: e.target.value will always contain + as first character so before applying any validation or doing calculation remove + first.

Suggestion:

You can use MaskedInput Lib also, it provides all these features.

Check this working Snippet:

class App extends React.Component{
   constructor(){
      super();
      this.state = {
         value: '+'
      }
      this._onChange = this._onChange.bind(this);
   }
   
   _onChange(e){
      let val = e.target.value;
      if(val.length > 0 && this._isNumeric(val)){
          this.setState({
              [e.target.name]: val
          })
      }else if(val.length == 1){
          this.setState({
              [e.target.name]: '+'
          })
      }
   } 
   
   _isNumeric(val){
       return /^\d+$/.test(val.substr(1));
   }
   
   
   render(){
      return(
         <div>
            <input name='value' value={this.state.value} onChange={this._onChange}/>
         </div>
      )
   }   
}

ReactDOM.render(<App/>, document.getElementById('container'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

<div id='container'/>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download