image onClick failing in React
class MyComponent extends React.Component { render () { const imageClick = () => { console.log('Click'); } return ( <div> <img src={require('/myfolder/myimage.png')} onClick={() => imageClick()} /> </div> ); } }
I've been playing with create-react-app and noticed that logo had pointer-events
css style set to none
which disables all the clicks. Not sure if that is your case. Just try to override that style in your img:
<img src='/myfolder/myimage.png' onClick={this.imageClick} style={{"pointer-events": "all"}} />
Well it does work in my case :
class MyComponent extends React.Component { imageClick = () => { console.log('Click!!!!'); } render () { return ( <div> <img src='http://www.libpng.org/pub/png/img_png/obj_64x64.png' onClick={this.imageClick} /> </div> ); }}ReactDOM.render(<MyComponent />, document.body);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
And the same version with a prop
(url) passed to the component, as well as as state
modification triggered when you click the image, as those two are important in React :
class MyComponent extends React.Component { constructor(props){ super(props); this.state = { clicked : false } } imageClick = () => { console.log('Click!!!!'); this.setState({ clicked: true }) } render () { return ( <div> <img src={ this.props.url } onClick={this.imageClick} /> { this.state.clicked && <div>You clicked me!</div> } </div> ); }}ReactDOM.render(<MyComponent url="http://www.libpng.org/pub/png/img_png/obj_64x64.png" />, document.body);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
Hope this helps!