简体   繁体   中英

How do I create an overlay in React?

I am currently trying to create an overlay on an image when hovering. I am able to get a box displayed on screen but it's not placed over the image.

featured.js

const Featured = ({ images }) => {
  if (!images || !Array.isArray(images)) return null;

  return (
    <section className={styles.featuredWrapper} id="work">
      {images.map((image) => {
        return (
          <div className={styles.wrap}>
            <GatsbyImage
              image={image.gatsbyImageData}
              alt="Link to the alt text"
              className={styles.featuredImg}
            />
            <div className={styles.featuredOverlay}>Test</div>
          </div>
        );
      })}
    </section>
  );
};

featured.module.css

.featuredImg {
  width: 100%;
  position: relative;
}

.featuredOverlay {
  position: absolute;
  background: black;
  opacity: 0.5;
  width: 100%;
  height: 100%;
  z-index: 1;
}

Every explanation I see revolves around the use of positions absolute and relative which makes me think my issue is how I am rendering my component. Am I using the position properties on the wrong elements?

import { useState } from "react";
import "./styles.css";

function Home() {
  const [showOverlay, setShowOverlay] = useState(false);

  return (
    <div>
      <div className="main-container">
        <div className="main-container__grid">
          <img
            src="https://miro.medium.com/max/2000/1*3SjDVyFY09xZ7NYMO5kj0g.png"
            className="test"
            alt="Placeholder"
            onHover={() => setShowOverlay(true)}
          />
          {showOverlay && <div className="targeting-box" />}
        </div>
      </div>
    </div>
  );
}

export default Home;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM