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

126
Visualizações
how to display elements when I click on it?

when I click on any button what displays is 1 and if i clicked again what I get is error saying that push is not a function .. it seems like index 1 in the button array have been pushed in state.num then the state.num have changed it,s type from array to number so I have 3 questions :

1-why the (1) have been selected to be pushed and not another element in the button array ??I cannot get that

2-why do the type of num has changed??is not it supposed to push the(1) as an array element ?it seems like it exchanged the num array with number 1 .. how did this happened while using push method??

3-what to do to display each element in the buttons array when I click on it??what did I do wrong?

here is my code

 class App extends React.Component {
  constructor(props){
    super(props);
    this.state={
      num:[],
    }
    this.handleclick=this.handleclick.bind(this);
  }
  handleclick (ele){
    this.setState({num:this.state.num.push(ele)})
  };
  render() { 
    const buttons = ["÷", 1, 2, 3, "*", 4, 5, 6,"+", 7, 8, 9, ".", 0, "-"];
    return (
      <div className="calculation-grid">
        <div className="output">
          <div className="previous-operand"></div>
          <div className="current-operand">{console.log(this.state.num)}</div>
        </div>
        <button className="span-two">AC</button>
        <button>DEL</button>
       {buttons.map((ele)=><button  onClick={()=>this.handleclick(ele)} key={ele}>{ele}</button>)}
        <button className="span-two">=</button>
</div>
    );
  }
}
 
export default App;
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

The issue is Array.prototype.push does not return the updated array (it's the length of the array). You can use the spread operator to push the values like below.

handleclick(ele) {
  this.setState({ num: [...this.state.num, ele] });
}

OR (using the callback function)

handleclick(ele) {
  this.setState((prevState) => ({
    ...prevState,
    num: [...prevState.num, ele]
  }));
}
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