'image onclick in react
I'm trying to add onClick function every time the user press the img. I tried some options that I found here at stack overflow. none of the above options works for me. I share some options that didn't work:
import React from "react";
export default function Movie(props) {
const imageClick = () => {
console.log('Click!!!!');
}
return <img alt = "movieposter" src = {props.link} className ="d-flex justify-content-start m-3" id="movie" onClick={() => imageClick}/>
}
import React from "react";
export default function Movie(props) {
imageClick = () => {
console.log('Click!!!!');
}
return <img alt = "movieposter" src = {props.link} className ="d-flex justify-content-start m-3" id="movie" onClick={this.imageClick}/>
}
import React from "react";
export default function Movie(props) {
imageClick = () => {
console.log('Click!!!!');
}
render ()
{
return (
<img alt = "movieposter" src = {props.link} className ="d-flex justify-content-start m-3" id="movie" onClick={this.imageClick}/>
)
}
}
Solution 1:[1]
import React from "react";
export default function Movie(props) {
const imageClick = () => {
console.log('Click!!!!');
}
return <img alt = "movieposter" src = {props.link} className ="d-flex
justify-content-start m-3" id="movie" onClick={() => imageClick()}/>
}
You are not invoking the function in the first example.
Functional component in React are stateless(instance less). So, they don't have access to this keyword. Therefore, the second and third example won't work. Simply, use the above example.
Solution 2:[2]
if you need to call func in an arrow function
import React from "react";
export default function Movie(props) {
const imageClick = () => {
console.log('Click!!!!');
}
return <img alt = "movieposter" src = {props.link} className ="d-flex
justify-content-start m-3" id="movie" onClick={() => imageClick()}/>
}
or if you want to pass you handler simply
import React from "react";
export default function Movie(props) {
const imageClick = () => {
console.log('Click!!!!');
}
return <img alt = "movieposter" src = {props.link} className ="d-flex
justify-content-start m-3" id="movie" onClick={imageClick}/>
}
or if you use class base components
import React from "react";
class Movie extends React.Component {
imageClick() {
console.log('Click!!!!');
}
return <img alt = "movieposter" src = {props.link} className ="d-flex
justify-content-start m-3" id="movie" onClick={this.imageClick}/>
}
Solution 3:[3]
Try this:
For your function:
function imageClick () {
console.log('Click!!!!');
}
and function call part:
<img alt = "movieposter" src = {props.link} className ="d-flex
justify-content-start m-3" id="movie" onClick={imageClick} />
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Adrian Mole |
| Solution 2 | Moh3n |
| Solution 3 | Özlem Akal?n |
