How can I use Onclick propertly with function in react js?

Viewed 33

Hey I have the follow issue, when I click in the buttons they don't go to your function. I don't understand what is wrong.

code:

import { useEffect, useState, useRef } from 'react';
import './feed.css';
import esquerda from '../../img/esquerda.png'
import image1 from '../../img/sagwabooks-carrossel-1.jpeg'
import image2 from '../../img/sagwabooks-carrossel-2.jpeg'

const Feed = () => {
  const carousel = useRef(null);

  const handleLeftClick = (e) => {
    console.log("entrou")
    e.preventDefault();
    carousel.current.scrollLeft -= carousel.current.offsetWidth;
  };

  const handleRightClick = (e) => {
    console.log("entrou2")
    e.preventDefault();

    carousel.current.scrollLeft += carousel.current.offsetWidth;
  };


  return (
    <div className="container">
      <div className="logo">
      </div>
      <div className="carousel" ref={carousel}>
        
        <div className="item" key={1}>
            <div className="image">
            <img src={image1} alt="image1" />
            </div>
        </div>

        <div className="item" key={2}>
            <div className="image">
            <img src={image2} alt="image2"/>
            </div>
        </div>
    </div>

     <div className="buttons-left">
        <button onClick={handleLeftClick}>
          <img className="img-esquerda" src={esquerda} alt="Scroll Left" />
        </button>
    </div>
    <div className="buttons-right">
        <button onClick={handleRightClick}>
          <img className="img-direita" src={esquerda} alt="Scroll Right" />
        </button>
    </div>

    </div>
  );
}

export default Feed;

the part of css of buttons :

  .img-esquerda{
    position:absolute;
    left:2%;
    top:30.5%;
    width: 50px;
    height: 50px;

  }
  .img-direita{
    position:absolute;
    left:96%;
    top:30%;
    width: 50px;
    height: 50px;
    transform: rotate(180deg);

  }

how you see when I click in the button it should go to function handleLeftClick but it won't, I don't know what is wrong

 <button onClick={handleLeftClick}>

I don't have any console messages about the problem. I try look to conventionals answers but no one works.

1 Answers

The error is in the css file,

the component of button wasn't adjusted, only the img inside the button was adjusted. the image was correctly in your right place but the button itself wasn't in that place. So when tried to click in the image, didn't call the function because is just the image not the button that inside has a image. so It needed to change css to the button and image are in the same place.

Related