David Ho
David Ho

Reputation: 287

How to give background color to image using CSS in ReactJS?

Currently, I am trying to apply an on-hover overlay to the <img /> like this:

const [hover, setHover] = useState(false);

        <img
          src={image}
          alt={alt}
          loading="lazy"
          onMouseOver={() => { setHover(true) }}
          onMouseOut={() => { setHover(false) }}
          style={{ zIndex: hover && 1,
                   transform: hover && 'scale(1.2, 1.2)', 
                   boxShadow: hover && '20px 20px 15px -4px #000000',
                   backgroundColor: hover && 'red',
                   transition: hover ? '0.5s' : '0.5s' }} />

However, I realized that the backgroundColor will be covered by the img itself. Is there any way to apply an overlay to the <img /> with backgroundColor or other styling props using inline styling? I have seen many tutorials, but all of them are using css styling. Much appreciated.

Upvotes: 1

Views: 805

Answers (1)

Noah
Noah

Reputation: 46

Could you try to write your code right this?

<img
        src={image}
        alt={alt}
        loading="lazy"
        onMouseOver={() => {
          setHover(true);
        }}
        onMouseOut={() => {
          setHover(false);
        }}
        style={
          hover
            ? {
                zIndex: 1,
                transform: 'scale(1.2, 1.2)',
                boxShadow: '20px 20px 15px -4px #000000',
                backgroundColor: 'red',
                transition: '0.5s',
              }
            : { transition: '0.5s' }
        }
      />

Upvotes: 1

Related Questions