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