Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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>
    )
}
}

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading