React: onClick not firing

Created on 9 Jul 2019  路  3Comments  路  Source: facebook/react

I can't seem to get the onClick event to fire at all. I've reduced my app to the following file:

index.js:

import React from 'react'
import { render } from 'react-dom'

const Index = () => {
  console.log('rendered')
  return <button onClick={() => console.log('hello')}>test</button>
}

render(
  <Index />,
  document.getElementById('app')
)

I get 'rendered' output to the console, but nothing when I click on the button.

package.json:

{ 
...
devDependencies {
    ...
    "react": "^16.8.4",
    "react-dom": "^16.8.4",
     ...
}
...
}

building inside a Laravel 5.2 app via:
browserify -t [ babelify --presets [ react es2015 ] ] resources/js/react/index.js -o public/js/test.js

Needs More Information

All 3 comments

This works fine https://codesandbox.io/s/infallible-fog-g37m8 If you can make a codesandbox, or a git repo that shows the problem, I could help more, but I can't comment further based on the above.

I'm closing this issue, but drop a comment if you can share a repro.

Thanks - I suspect the issue was with Babel or something else in the toolchain which meant that it wasn't compiling correctly (it was passing onChange as a normal prop).

I've fixed it by reinstalling browserify/babel etc. and it now works using
browserify resources/js/react/index.js -o public/js/test.js -t [ babelify --presets [ @babel/preset-env @babel/preset-react ] ]

Faced similar issue and found that the onClick on button is not working if any attribute of the button is updated.

Minor changes in your code here can reproduce this: https://codesandbox.io/s/infallible-fog-g37m8

Try this:
```import React from "react";
import { render } from "react-dom";

setTimeout(() => {
const x = document.getElementById("some-btn");
x.disabled = false;
console.log(x);
}, 3000);

const Index = () => {
console.log("rendered");
return (

);
};

render(, document.getElementById("root"));

Was this page helpful?
0 / 5 - 0 ratings