How can I modify the CSS styles of multiple elements triggered by an event in React?

Can you guide me on how to manipulate style attributes in React? I have experience with query selectors, but I've learned that they may not be the best approach due to state changes in React. Specifically, how can I access and update style attributes in React from a different element's event?


const elements = document.querySelectorAll(".option-item");

function changeBackground() {
    elements.forEach((element) => {
        element.style.background = "red";
    });
}

<div className="options-panel" onMouseOver={changeBackground}>
 <div className="option-item">1</div>
 <div className="option-item">2</div>
 <div className="option-item">3</div>
 <div className="option-item">4</div>
</div>
.options-panel{
  background-color:black;  //<<---when I hover over this corresponding element
}

.option-item{
  background-color:blue    //<<---all elements with this classname change to "red"//
}

Answer №1

When passing the event to your function, you are specifying which property of the event you want to call. In this scenario, you specifically need to access the target property. Modify your code as follows:

const elements = document.querySelectorAll(".option-item")

function changeBackground(e) {
    e.target.style.background = "red";
}

<div className="options-panel" onMouseOver={changeBackground}>
 <div className="option-item">1</div>
 <div className="option-item">2</div>
 <div className="option-item">3</div>
 <div className="option-item">4</div>
</div>

Answer №2

In addition to agreeing with the previous response, I'd like to mention that it may be necessary to include an onMouseLeave function to restore the element's initial background color.

Answer №3

//DEFINE INITIAL STATE VALUES FOR ATTRIBUTES//
const [panelWidth, setPanelWidth] = useState("50px");
const [opacity, setOpacity] = useState(0);

//CUSTOM FUNCTIONS TO TOGGLE WIDTH AND OPACITY//
function toggleStretch() {
    if (panelWidth === "50px") {
      setPanelWidth("300px");
      setOpacity(1);
    } else if (panelWidth === "300px") {
      setPanelWidth("50px");
      setOpacity(0);
    }
  }
//USE EVENT TO TRIGGER FUNCTION AND APPLY STYLES USING STATE//
  <div
        className="options-panel"
        style={{ width: panelWidth }}
        onMouseOver={toggleStretch}
        onMouseLeave={toggleStretch}
      >
        <div className="options-item">
          <div>
            <FontAwesomeIcon icon={faHome}></FontAwesomeIcon>
          </div>
          <p style={{ opacity }}> Home</p>
        </div>
        <div className="options-item" onClick={toggleListHandler}>
          <div>{iconState ? <FontAwesomeIcon icon={faFolder} /> : <FontAwesomeIcon icon={faFolderOpen} />} </div>
          <p style={{ opacity }}> About</p>
        </div>
  </div>

To ensure smooth transitions add the following CSS:

.options-panel {
 
  transition-duration: 0.5s;
}

.options-item {

  transition-duration: 0.3s;
}

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

What is the most effective way to delete a single value from a key with multiple values stored in local storage?

This question has come up before, but the solutions provided didn't work for me, which is why I am asking it again. Currently, I am storing values in an array that is then stored in local storage. Here is the object: data.items - 0: {id: 190217270, ...

Utilizing the CSS REM unit to define element dimensions

I recently discovered the versatility of using the REM unit for sizing elements, not just font sizes. It works really well in conjunction with the HTML font-size property. html { font-size:1vw } @media all and (max-width:720px) { html { font-size:10px ...

Ways to verify if all javascript and css files have been successfully loaded

I have been exploring different ways to notify users if certain resources do not load correctly. So far, I have come across the following methods: For CSS, I stumbled upon an example in the source code of Trello: <div id="nocss"> Your browser ...

What is the best way to choose the first div when there are multiple divs with the same name?

Is there a way to target only the first div with a specific class in a series of divs with the same name using CSS? Here is an example scenario: <div class="div">dsdas</div> <div class="div">123</div> <div class="div">73</ ...

Is there a way to assign an id to a hyperlink when it is clicked in order to trigger specific CSS changes?

I am working on a navigation bar that includes links passing data through GET to display information from the database. The challenge is styling these links with the id 'selected' to show which one is currently active. <a href="./welcome.php? ...

issues with the functionality of bootstrap modal

I'm currently working on a project where I need to set up a modal popup using bootstrap. The website I'm working on is organized by departments, so the only part of the code that I have control over is the main body of the site. I have included t ...

Issue with CSS background image not showing up in Internet Explorer 8

Do you have any suggestions for tweaking the CSS to accommodate the compatibility issue with viewing our intranet sites in IE 8? The CSS image background is not displaying properly. Please keep in mind that the HTML and CSS work fine in Chrome, as well as ...

Selenium Nightwatch's setValue function on input field is displaying only the final character

In my attempt to test a React input by passing in the value of "My test" with the code below, only the last letter "t" appears on the screen and in the component value. this.useXpath() .waitForElementVisible('@subsetDialogNameInput') .cle ...

Prevent touching the pseudo content of an element

My issue involves a toggle button component where I have utilized the ::before pseudo class to add text. The problem arises when clicking on the text within the toggle button causes the button's state to change. How can this be prevented? Here is the ...

steps for applying a vertical-align:bottom with an additional 10px offset

Can you show me how to have two inline-blocks with the second one positioned 10 pixels up from the bottom? I'm not sure how to do this. Here is a snippet of my code: .test1{ display:inline-block; border: 1px solid red; min-height: 50px; } .tes ...

The numbering in the list does not align vertically with the corresponding content

I am attempting to create an ordered list with collapsible sections inside the li elements. The goal is to display basic information about a specific context, and when clicking on a link, additional details are shown. While the code is functional, I am fac ...

Testing the React context value with React testing library- accessing the context value before the render() function is executed

In my code, there is a ModalProvider that contains an internal state managed by useState to control the visibility of the modal. I'm facing a dilemma as I prefer not to pass a value directly into the provider. While the functionality works as expecte ...

Error message: webpack's CLI has been relocated to its own package named webpack-cli

I've been diving into the world of ReactJS and decided to follow a tutorial here on installing React. This is all new to me. After completing the installations as demonstrated in the video, I proceeded to run this command in the project's main f ...

Is there a way to include an instance variable as a CSS rule in Rails?

Assume I have the following ActiveRecord class: ......... store :skin_properties, accessors: [ :background_color, :font_size, :font_family, :color ] ......... This class saves values in the format shown below: {"background_color"=> ...

The search bar is visible on desktop screens and can be expanded on mobile devices

Check out my code snippet below. <style> #searchformfix { width: 50%; border-right: 1px solid #E5E5E5; border-left: 1px solid #E5E5E5; position: relative; background: #fff; height: 40px; display: inline-block; border: ...

Implementing a loading spinner in React Native until the component is fully mounted

I am dealing with a List component that takes some time to load. I am trying to display a spinner until the component is loaded and mounted, but all my attempts have been unsuccessful. Here is the approach I am currently attempting: class List extends R ...

Learn how to assign an image to a div element when it is collapsed, and then reveal the content when clicked on to expand

I am working on a three div with expand collapse functionality. When I expand one div, I want to set some image to the other divs. And when I go back to normal mode, I need the original content that was inside each div. $("a.expansion-btn").click(functi ...

Experiencing difficulties when uploading information to an API in a React JS application

Trying to Send Data via React to Contact Form API Having issues trying to send input data through the API when clicking submit button. The error encountered is that the API call should look like this Example Link However, it calls in a different way Diff ...

In ReactJS, it has been observed that the Checkbox consistently displays as true, but

I am facing a very specific issue. The checkbox with controlled component is functioning correctly on my local machine, but when I deploy the code online, it seems to have a problem. While everything else works fine (check/uncheck) and the data values are ...

Stylish web page tabs with diverse visuals

Is it possible to have the background image become focused when a user clicks on one of the images? I want all icons except the clicked one to be greyed out, with the colored version showing only for the selected icon. Currently, the color image of each i ...