Limit number of characters in reactjs
<p>I have a input box where serial number has to be filled in. The max character is 32 so the texting should stop when number of character reaches to 32. I tried to do in 2 ways but both ways are not working. The first way i tried to update the state with custom function where some pattern is defined. Second way i tried to pass the pattern in Textfield component as a props. The component is of react-mdl and it shows the error when the pattern mismatch. </p>

<p><strong>Second way that i tried to change the pattern that is passed in the Textfield component as a prop by default</strong></p>

<pre><code>&lt;Textfield
    onChange={(event)=&gt; {this.handleInputChange(event)}}
    pattern="-?[0-9]*(\.[0-9]+)?"
    error="Input is not a number!"
    label="Device Serial Number"
    floatingLabel
/&gt; 
</code></pre>

<p>to</p>

<pre><code>&lt;Textfield
    onChange={(event)=&gt; {this.handleInputChange(event)}}
    pattern="-?[0-9]*(\.[0-9]{6,32})?"
    error="Input is not a number!"
    label="Device Serial Number"
    floatingLabel
/&gt; 
</code></pre>

<p><strong>first way(with first Textfield example)</strong></p>

<pre><code>const extract = (str, pattern) =&gt; (str.match(pattern) || []).pop() || '';

const extractPattern = (str) =&gt; extract(str, "-?[0-9]*(\.[0-9]+)?");

const limitLength = (str, length) =&gt; str.substring(0, length);


export default class App extends Component {
  constructor(props){
    super(props);
    this.state = {max_char:32, limit:{}};
    this.handleChange = this.handleChange.bind(this);
  }


  handleChange(charLength){
      console.log('charLength',charLength);
      this.setState({
        max_char:32 - charLength.length,
        limit:limitLength(extractPattern(charLength), 32),
      });
      console.log('charLength', charLength);
      // console.log('limitLength', this.state.limit);
  }
</code></pre>