Home > front end >  image onclick in react
image onclick in react

Time:01-02

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}/>
    )
  }
}

CodePudding user response:

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.

CodePudding user response:

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}/>
 }
  • Related