What is the best way to manage the appearance of multiple elements in React simultaneously?

I have a fun little game that I've been working on. Check it out - here

In my game, when you hover over a square, it turns blue. If you hover over it again, it turns white. I achieve this by applying styles to the event target on hover.

const handleMouseEnter = (e) => {
    const hoveredDiv = e._targetInst.pendingProps.value;
    e.target.className = 'blue'
    if (hoveredSquares.includes(hoveredDiv)) {
      dispatch(actions.removeFromHovered(hoveredDiv))
      e.target.style.backgroundColor = 'white';
    } else {
      dispatch(actions.addToHovered(hoveredDiv))
      e.target.style.backgroundColor = 'blue';
    }
  }

However, I encountered an issue when I tried to change the game mode to 10x10. I needed to make all squares white again, essentially restarting the game. Even though the previously hovered squares remained blue. Here's the code for the squares:

const generateSquares = () => {
 if (!currentMode || currentMode === 0) {
  return
 }
 const array = Array.from(Array(currentMode), () => Array(currentMode).fill(currentMode))

 return (
  <Box style={{ marginTop: 20 }}>
    {array.map((rowEl, rowIndex) => {
      return (
        <Box
          key={rowIndex}
        >
          {rowEl.map((_, colIndex) => {
            return (
              <Box
                value={`row ${rowIndex + 1} col ${colIndex + 1}`}
                onMouseEnter={e => handleMouseEnter(e)}
                key={colIndex}
              ></Box>
            )
          })}
        </Box>
      )
    })}
  </Box>
)

In Vanilla JS, I would have used querySelectorAll to control the styles of multiple elements. In React, however, I'm looking for a way to achieve this using hooks. Any suggestions would be greatly appreciated. Thank you!

Answer №1

To start, create a Base square component and assign state to each element.

const [isHovered, setIsHovered] = useState(false)
return <Square
 onMouseEnter={() => setIsHovered(true)}
 onMouseLeave={() => setIsHovered(false)}
 className={isHovered ? blue : white} />

Whenever you need to make changes to the game, all components will need to be re-rendered, causing states to reset.

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

How can Bootstrap 4 be utilized to achieve a responsive height on a single page application with no scrolling?

Embarking on the journey of responsive website design as a beginner in front end development, I am currently working on creating a basic angular chat application with bootstrap. Keeping responsiveness in mind throughout the design process is my goal, but I ...

Creating a grid layout with a row of buttons

I'm currently working on aligning buttons within a div to achieve the desired effect shown in the image below. My goal is to have all buttons centered on the page, with the small circles placed in a separate div as they are initially invisible and it& ...

Utilizing border-image property to showcase four dots in each corner of my div container

I'm having trouble applying a gradient color to my border using the border-image property. When I use border-image: linear-gradient(-180deg, #2D6BD0 0%, #83B8FF 100%);, I'm only seeing a single dot in each corner of my DIV. Does anyone know why t ...

Utilizing _.partial on a single-argument function

Currently, I am in the process of refactoring code within a react.js application. There is an element that utilizes Underscore.js _.partial on a function that already has one argument. Is there any real benefit to doing this? I can see how it works based ...

The div above the footer seems to be interfering with the styling of the footer. Is there a solution to

I am currently working on implementing a Help functionality for our users. In order to do this, I have placed a div right above my footer. However, I am facing an issue where the styling of my div is affecting the footer in ways that I cannot figure out. ...

Getting tags with text containing specific substring by utilizing CSS selectors

Here is the HTML snippet I am working with: <tr bgcolor="#DEDEDE"> <td> <b>OK:Have idea</b> </td> <td> <b>KO:Write code</b> </td> <td> <b>KO:Ru ...

Red-colored text (as displayed in Firefox) is not recognized by JSoup when parsing HTML <img> tags

UPDATE: I was able to answer my own question. JSoup can indeed find all image tags. I've been attempting to scrape content from but encountered a problem. In the website's source code, the main images are displayed in red font, which seems to ...

Obtaining IDs of Divs that have been Dragged into a Drop Zone upon Clicking a Button using JavaScript

I'm currently working on a solution to extract the ids of dragged divs once they have been placed in the drop zone. Each drag component is assigned an id ranging from drag1 through drag8, while the drop zone is labeled as div drop zone. Since there a ...

What could be preventing this bootstrap carousel slider from transitioning smoothly?

I've created a CodePen with what I thought was a functional slider, but for some reason, the JavaScript isn't working. The setup includes bootstrap.css, jquery.js, and bootstrap.js. I'm having trouble pinpointing what's missing that&apo ...

Excessive image display | HTML and CSS synergize

I am having some trouble with my image gallery. Each image is displayed as a vertical column and has zooming effects when hovered over. Clicking on an image should show it in full screen with a caption. The problem arises when dealing with images that are ...

Stop the background from scrolling and prevent auto-jumping to the top on mobile devices

When users click on the hamburger icon in the top right of our mobile site, I want the drop-down menu to appear and be scrollable without the background scrolling. I tried using JavaScript to set the body to fixed when the menu icon is clicked, but this ca ...

Implementing ExpressJS with MongoDB on a MERN Development Stack

After configuring my ExpressJS & MongoDB client and running Nodemon, I consistently encounter the following warning: "DeprecationWarning: current Server Discovery and Monitoring engine is deprecated, and will be removed in a future version. To use the ...

Encountering issues while attempting to pass a function into axios.then and catch and receiving errors

axios.post('http://localhost:3000/api/v1/login', { email: this.state.email, password: this.state.password }, { headers: { "Access-Control-Allow-Origin": "*", ...

Encountering a React.js page not found error upon refreshing or when clicking a link directly

I am currently working on a React project hosted at the following link: . When you scroll down, you will come across a section labeled "PRODUCT CATEGORIES". If you click on one of the categories, such as https://i.sstatic.net/QDHh2.png, it should take you ...

Having trouble finding two p-col-6 elements side by side in the PrimeNG FlexGrid with Angular?

I have integrated Flex Grid into my Angular7 project. In the initial state, I am able to display two p-col-6 elements side by side without any issues. However, when I try to rearrange them in p-col-12, they no longer align properly. Here is a detailed expl ...

What is the reason behind material-ui modules appearing in both node_modules and src folders following Webpack 4 tree shaking process?

Experience the Cloud Native Interactive Landscape, a unique browser-based tool that utilizes a static React app to showcase the cloud native ecosystem: Explore the application Check out the source code You have the ability to interactively view the resu ...

Tips for assigning a default value when an error occurs

Currently diving into the world of React and experimenting with rendering 10 pieces of data from a specific API. After crafting a function to iterate through the fetched information, extracting the title and image has been quite the challenge: for (let ...

Looking for a way to keep the mobile ad unit fixed at the bottom of the screen

I am currently working on incorporating a 320x50 mobile ad into the mobile version of my website. The goal is to have the ad fill the entire width of a mobile device. However, the issue I'm facing is that the ad appears small and does not stretch acro ...

Using the calc function to define input width may not yield the expected results

I am facing an issue where I have an input element with width: calc(100% - 100px); and no padding/margin/border. Next to this input, I want to place a div with position: inline-block; and width: 100px;. The problem is that the div is going to the next lin ...

Conceal a table with jQuery

Is there a way to initially conceal a table on page load only to reveal it with a sliding animation when a specific link is clicked? I have attempted using the following code to hide the table: $('.table_div').hide(); I have enclosed the table ...