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

107
Visualizações
why onClick isn't working on my react project

onclick isn't working on my react component, here is my code:

const listItems = xox.map((nums) =>
    <Square key={nums.index} cont={nums.content} onclick={function (){
        alert();
    }}/>
);

also i tried this but alert working on the when render the page:

    <Square key={nums.index} cont={nums.content} onclick={alert()}/>

my app function:

function App() {
  return (
    <div className="App">
        <header>
          <img src={logo} alt="React logo"/>
            <h1>XOX</h1>
        </header>
        <div className="playground">
            {listItems}
        </div>
    </div>
  );
}

Square.js

import React from "react";
export class Square extends React.Component {
    render() {
    return (
        <div className="square" onClick={this.props.onclick}>
            {this.props.cont}
        </div>
    )
}
}
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

You need to make sure your Square component accepts and then uses an onclick prop. For example, something like:

const Square = ({ cont, onclick }) => (
  <div onClick={onclick}>{cont}</div>
);

Otherwise the prop will be ignored, since it's not used inside the component.

also i tried this but alert working on the when render the page:

Yes, you need to pass a function as a prop, not invoke the function then pass the result as a prop. This:

return <Square key={nums.index} cont={nums.content} onclick={alert()}/>

is equivalent to doing

const result = alert();
return <Square key={nums.index} cont={nums.content} onclick={result}/>;

So you instead need

onclick={() => alert()}

(or with the function keyword as you're already doing, though it's less terse)

If possible, I'd also suggest using the standard capitalization for React click handlers, which is onClick, not onclick - there's less chance of confusing people that way.

about 4 years ago · Juan Pablo Isaza Relatório

0

try using arrow functions:

<Square key={nums.index} cont={nums.content} onClick={() => alert('hello world')}/>
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