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"}} />
Your code looks fine and here is the working sample with image onClick
. I have tested on my machine Chrome 16.0
working fine.
<!DOCTYPE html>
<html>
<head>
<title>React Image Click</title>
<meta charset="utf-8">
<script crossorigin src="https://unpkg.com/[email protected]/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/[email protected]/umd/react-dom.development.js"></script>
<script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>
<script type="text/jsx">
class MyComponent extends React.Component {
imageClick = () => {
console.log('Click!!!!');
}
render () {
return (
<div>
<img src='/myfolder/myimage.png' onClick={this.imageClick} />
</div>
);
}
}
ReactDOM.render(
<MyComponent />,
document.getElementById("app")
);
</script>
</head>
<body>
<div id="app"></div>
</body>
</html>
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!