Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

165
Views
Constructor Question (react Javascript) for incrementing

how do i make a text input inside of a React component that will show a text box with a submit button , next to it there should be a number that will be incremented each time i click "submit". The increment value (that is added to the counter) will be the length of each word that was submitted.

so lets say i write in the text box "hi" (2 letters) and click submit - my counter should show 2 then if i write there "welcome" - not the counter will add 7 ==> so it will show 9

the local state should be inside of the class component.

Thanks :)

this is what i got :

import React, { Component } from 'react'


export class TextInput extends Component {
    constructor(){
        super()
        this.state = {
          count: 0
        }
        this.handleClick = this.handleClick.bind(this)
      }
      handleClick(){
        this.setState(prevState => {
          return {
            count: prevState.count + 1
          }
        })
      }


      


      render(){
        return(
          <div>
            <h1>{this.state.count}</h1>
               <input type="text" value={this.state.value} onChange={this.handleChange} />
            <button onClick = {this.handleClick}>Change</button>
          </div>
        )
      }
    }
export default TextInput
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

You need to use the value state and add its length to the count state:

import React, { Component } from "react";

export class TextInput extends Component {
  state = {
    count: 0,
    value: "",
  };
  handleClick = () => {
    this.setState((prevState) => {
      return {
        count: prevState.count + prevState.value.length,
        value: "",
      };
    });
  };

  handleChange = (e) => {
    this.setState({ value: e.target.value });
  };

  render() {
    return (
      <div>
        <h1>{this.state.count}</h1>
        <input
          type="text"
          value={this.state.value}
          onChange={this.handleChange}
        />
        <button onClick={this.handleClick}>Change</button>
      </div>
    );
  }
}
export default TextInput;
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!