I am trying to make a favorite button in the js Act, that by clicking the icon with the classname"far fa-Heart" it changes to classname"fas fa-Heart"

Asked

Viewed 42 times

-1

import Cama from 'cama.png'
import React from 'react'
import styles from './styles.module.scss'

export default function Recommend() {

    const [favorit, setFavorit ] = useState();

    
    return (
        <div className={styles.cardContext}>
            <div>
            <p><i  className="far fa-heart" id="item"></i></p>

                <img src={Cama} alt="Cama" />
            </div>
         </div>
}
  

1 answer

0


There are some ways to do this by following what you were doing would look like this:

import Cama from "cama.png";
import React from "react";
import styles from "./styles.module.scss";

export default function Recommend() {
  const [favorite, setFavorite] = useState(false);

  // Confere pra ver se o valor do estado está como "true"
  // Se estiver ele retorna a classe com o coração preenchido
  const checkIfIsFavorite = () => (favorite ? "fas fa-heart" : "far fa-heart");

  // Altera o "favorite" para o contrário ao ser executada
  const handleToggleFavorite = () => setFavorite((previous) => !previous);

  return (
    <div className={styles.cardContext}>
      <div>
        <p onClick={handleToggleFavorite}>
          <i className={checkIfIsFavorite} id="item"></i>
        </p>
        <img src={Cama} alt="Cama" />
      </div>
    </div>
  );
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.