What is the best way to apply a background color to an image in ReactJS using CSS?

My current challenge involves applying an on-hover overlay to the <img /> element in this manner:

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' }} />

I have come across an issue where the backgroundColor property gets covered by the img itself. Is there a way to achieve an overlay on the <img /> while using inline styling for background color or other styling properties? Most tutorials I find use CSS for this purpose. Any help is greatly appreciated.

Answer №1

Can you attempt to implement your code in the following manner?

<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' }
        }
      />

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Incorporate a background image and overlay it with CSS animations for a dynamic effect

I have set up a fiddle, but it seems like the display is not quite right. You can check it out here - http://jsfiddle.net/kVNQb/ - although it might be helpful to take a look at the code regardless. The snow animation I am using is from this website: My ...

Using the MVC framework, create a hyperlink with custom CSS styling by

Having trouble getting a specific class to override the default styles for a:link @Html.ActionLink("Back to List", "Index", null, new { @class = "htmlactionlink" }) CSS a:link, a:visited, a:active, a:hover { color: #333; } .htmlactionlink { co ...

Issue with defaultValue Prop in Radix UI Accordion when used with Dynamic Child Components

Issue Description: Encountering a problem while utilizing Radix UI's Accordion in a Next.js project. The defaultValue prop seems to be ineffective when the Accordion's children are generated dynamically. Despite setting the defaultValue, the acco ...

Is it possible to access the ID element of HTML using a variable in jQuery?

I have fetched some data from a JSON ARRAY. These values include Value1,Value2, and Value3. Additionally, I have an HTML checkbox with an ID matching the values in the array. My goal is to automatically select the checkbox that corresponds to the value re ...

What is the best way to show the selected values of dropdown and checkboxes on a redirected page for confirmation using PHP?

<form action="action.php" method="POST" target="_self"> <table class="main" border="1" height="100%" align="center">t; <h3> <p id="id1" style="background-color: #9FF" >Registration form</p></h3> <tr><t ...

Please provide the text input for the specified version numbers (1.1, 1.2, 3.0, etc.)

I'm currently working on a form that includes a section for searching by version number: <label class="formLabel">Version</label> <html:text property="valueVersion" styleClass="value" tabindex="11"/> <br/& ...

How to remove an extra horizontal scroll bar from a fixed-header HTML table?

While working on updating my HTML tables to have fixed headers, I followed online examples that suggest making table-layout fixed, thead and tbody blocks, setting height constraints for tbody, and applying overflow-y to tbody. The result is functional as m ...

Extracting multiline value from a textarea using JavaScript

I'm trying to extract a multiline value from a textarea using JavaScript or jQuery and store it in a cookie. Below is the code snippet I am using: HTML: <textarea id="cont" cols="72" rows="15"> JavaScript: var txt = $('#cont').val( ...

Achieving consistent spacing between elements within a column in Bootstrap 5

Picture a bootstrap column filled with various elements such as divs, paragraphs, and links. How can I evenly space these elements inside the column without using margins or padding? I am looking for an automatic way for the elements to be spaced equally a ...

Creating a Fractional Division Formula in HTML

My goal is to create code that displays various mathematical formulas. The formula I am focusing on right now is for the mean (average) and it currently looks like this: ∑n⁄n: <span class="frac"><sup>&sum;n</sup><span> ...

Mapping Form Fields (with Formik)

Currently, the Formik/Yup validation setup in my form is working perfectly: export default function AddUserPage() { const [firstName, setFirstName] = useState(""); const [email, setEmail] = useState(""); return ( <div> <Formik ...

"Revamping Form Layouts with Bootstrap's Horizontal Alignment and Column

I am diving into a new adventure by working with a Bootstrap Horizontal Form for the first time. I have followed their example and now trying to convert it into 4 columns. In my design, Columns 1 and 3 will house field labels while Columns 2 and 4 will con ...

Refresh Induced Unstyled Content (RIUC) when reloading with next.js and custom styles

Every time I reload my page, I notice a font flickering issue while using global styles from styled components in next.js. https://i.sstatic.net/Xhct8.gif The font files are located in public/fonts/Inconsolata. I have searched extensively on Spectrum ch ...

Make sure to always display the browser scrollbar in order to avoid any sudden page

Question: How can I ensure the scrollbar is always visible in a browser using JavaScript? I've noticed that some of my web pages have a scrollbar while others do not, causing the page to jump when navigating between them. Is there a way to make t ...

Methods for Expanding a Div within an Oversized Row, Despite Height Constraints

I have a situation where I need to adjust the height of a cell in a table. One of the cells contains a larger element that causes the row to expand vertically. I also have another cell with a div element set to 100% of the cell's height. However, I wa ...

React/Next Component Changes State and Clears it in useEffect

Currently, I am faced with an issue while attempting to fetch data from an API. The problem arises during the rendering process since the useEffect function is being called multiple times. Surprisingly, everything works perfectly fine during the initial pa ...

Validating a form using ReactJS can be a bit time-consuming as it involves

Having an issue with React validation on a login form. When I click submit after entering the correct email and password, it returns false initially but changes to true only after the third attempt. Why does the formValid state take time to update? How can ...

Utilize HTML5 and JavaScript to calculate the velocity of a device by employing devicemotion and device

Can device speed in km/h be calculated using the devicemotion/deviceorientation HTML5 API? I am interested in determining whether a user is walking, running, or stationary without relying on the geolocation API, which may not be accurate indoors. ...

Maintain original pitch of HTML video content (preservesPitch, mozPreservesPitch, webkitPreservesPitch)

I am attempting to turn off the preservesPitch feature on a video element that is playing in slow motion by adjusting the video's playbackRate. In Chrome, video.webkitPreservesPitch is not defined, and changing it to false or true doesn't affect ...

Tips for showcasing chats with the most recent message highlighted

As I work on my web app using Laravel, I have encountered an issue where I need to scroll down to see the newest messages when there are many conversations. Here is how the chats display on page load I want to focus on displaying the newest message first. ...