Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

163
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda