Search code examples
reactjshovermouseevent

How to show button while hover over box using react?


I am working on a project, it is an online shop in react. I would like to make "Quick view" and "Add to cart" buttons visible only while hovering over the product box they're in. Also, they should be clickable. Code of the ProductBox below`

const ProductBox = ({ name, price, promo, stars }) => (
  <div className={styles.root}>
    <div className={styles.photo}>
      {promo && <div className={styles.sale}>{promo}</div>}
      <div className={styles.buttons}>
        <Button variant='small'>Quick View</Button>
        <Button variant='small'>
          <FontAwesomeIcon icon={faShoppingBasket}></FontAwesomeIcon> ADD TO CART
        </Button>
      </div>
    </div>
    <div className={styles.content}>
      <h5>{name}</h5>
      <div className={styles.stars}>
        {[1, 2, 3, 4, 5].map(i => (
          <a key={i} href='#'>
            {i <= stars ? (
              <FontAwesomeIcon icon={faStar}>{i} stars</FontAwesomeIcon>
            ) : (
              <FontAwesomeIcon icon={farStar}>{i} stars</FontAwesomeIcon>
            )}
          </a>
        ))}
      </div>
    </div>
    <div className={styles.line}></div>
    <div className={styles.actions}>
      <div className={styles.outlines}>
        <Button variant='outline'>
          <FontAwesomeIcon icon={faHeart}>Favorite</FontAwesomeIcon>
        </Button>
        <Button variant='outline'>
          <FontAwesomeIcon icon={faExchangeAlt}>Add to compare</FontAwesomeIcon>
        </Button>
      </div>
      <div className={styles.price}>
        <Button noHover variant='small'>
          $ {price}
        </Button>
      </div>
    </div>
  </div>
);

Solution

  • Please follow the below code:

    import React, {useState} from "react";
    
    export default function ShowButtonHover() {
        const [style, setStyle] = useState({display: 'none'});
    
        return (
            <div className="App">
                <h2>Hidden Button in the box. Move mouse in the box</h2>
                <div style={{border: '1px solid gray', width: 300, height: 300, padding: 10, margin: 100}}
                     onMouseEnter={e => {
                         setStyle({display: 'block'});
                     }}
                     onMouseLeave={e => {
                         setStyle({display: 'none'})
                     }}
                >
                    <button style={style}>Click</button>
                </div>
            </div>
        );
    }