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

106
Views
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 answers
Answer question

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 Report

0

try using arrow functions:

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