others-Why my onclick function is not working inside a react component?
1. Purpose
In this post, I would demo how to solve the onClick
function not working when using react to write a component.
2. Environment
- npm and node version:
➜ ~ npm version
{
npm: '8.1.2',
node: '17.1.0',
v8: '9.5.172.25-node.13',
uv: '1.42.0',
zlib: '1.2.11',
brotli: '1.0.9',
ares: '1.18.1',
modules: '102',
nghttp2: '1.45.1',
napi: '8',
llhttp: '6.0.4',
openssl: '3.0.0+quic',
cldr: '39.0',
icu: '69.1',
tz: '2021a',
unicode: '13.0',
ngtcp2: '0.1.0-DEV',
nghttp3: '0.1.0-DEV'
}
3. The code and solution
3.1 The code that causing problem
I am writing a very simple react component, which is just a square button, it would print on click 222
when user click it.
class Square extends React.Component {
onClickMe() {
console.log("on click 222");
}
render() {
return (
<button className="square" onClick={this.onClickMe()}>
{this.props.value}
</button>
);
}
}
But when I run the code, I got this:
You can see that the code is not working as expected, it just show 9 on click 222
after startup(Because we have 9 squares), but we haven’t click any of the square yet. When I click a square, nothing happens, onClick
is not working. Why?
3.2 The solution
According to this document, we should pass a function reference instead of passing the function itself to a component in the react applications.
class Square extends React.Component {
onClickMe() {
console.log("on click 222");
}
render() {
return (
<button className="square" onClick={this.onClickMe}>
{this.props.value}
</button>
);
}
}
The key point is:
<button className="square" onClick={this.onClickMe}>
Notice we have removed the function call ()
, just pass this.onClickMe
, which is a function pointer or reference.
Re-run the app, we got this:
You can see that there is no 9
logs any more, when we click any of the square, the log is showing.
4. Summary
In this post, I demonstrated how to solve the onClick
not working problem when using react component, To write a component with function calls on events, we should notice that we should pass the reference not the function itself . That’s it, thanks for your reading.