Sebastián Ardila
Sebastián Ardila

Reputation: 137

React image onClick not executing

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

Upvotes: 1

Views: 768

Answers (3)

Evren
Evren

Reputation: 4410

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}

Upvotes: 3

Hans Murangaza DRCongo
Hans Murangaza DRCongo

Reputation: 860

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>

Upvotes: 0

user11847513
user11847513

Reputation:

Please try to use this one

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

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

Upvotes: 1

Related Questions