Home > Software engineering >  React image onClick not executing
React image onClick not executing

Time:04-30

Hello I have a React project and I want to trigger an action when I click an image but the function is not executing. I want to use this to access another View using react-router-dom history. Here is my code:

import React from "react";
import "perfect-scrollbar/css/perfect-scrollbar.css";

import { useHistory } from 'react-router-dom';

// @material-ui/core components
import { makeStyles } from "@material-ui/core/styles";

import image from '../assets/tesis/IMG_8006.JPG'
import image2 from '../assets/tesis/IMG_8008.PNG'
import image3 from '../assets/tesis/IMG_8007.PNG'


import styles from "assets/jss/material-dashboard-pro-react/layouts/adminStyle.js";


const useStyles = makeStyles(styles);

export default function Dashboard(props) {
  const classes = useStyles();
  const history = useHistory();

  const handleClick = () => {
    console.log("Click")
  }

  return (
    <div className={classes.wrapper} style={{flex:1, justifyContent:'center', display:'flex' , alignItems:'center' , backgroundImage: `url(${image})`, height: '100vh', backgroundPosition: 'center', backgroundRepeat: 'no-repeat', backgroundSize:'cover'}}>
      <img src={image2} style={{width:'70vh', alignSelf:'center', position: 'absolute'}} alt="Error" ></img>
      <img src={image3} style={{width:'50vh'}} onClick={() => {
        handleClick();
      }} alt="Error"></img>
    </div>
  );
}

CodePudding user response:

In first image you give position absolute with 70vh so it takes space of the second image. You are not able to click second image because of this problem otherwise logic is fine

<img src={image2} style={{width:'70vh', alignSelf:'center', position: 'absolute'}} alt="Error" ></img>
<img src={image3} style={{width:'50vh'}} onClick={() => {
        handleClick();
      }} alt="Error"></img>

But I would change like this onClick={handleClick}

CodePudding user response:

Please try to use this one

const handleClick = (e) => {
    console.log("Click", e)
  }

<img src={image3} style={{width:'50vh'}} onClick={handleClick} alt="Error"></img>

CodePudding user response:

Can you try to remove the position absolute from the first image? Maybe it is positioning on top of the second one

<div className={classes.wrapper} style={{flex:1, justifyContent:'center', display:'flex' , alignItems:'center' , backgroundImage: `url(${image})`, height: '100vh', backgroundPosition: 'center', backgroundRepeat: 'no-repeat', backgroundSize:'cover'}}>
      <img src={image2} style={{width:'70vh', alignSelf:'center', }} alt="Error" ></img>
      <img src={image3} style={{width:'50vh'}} onClick={() => {
        handleClick();
      }} alt="Error"></img>
    </div>
  • Related