Change the appearance of a specific div within a collection of div elements using React

I'm currently working on a visualizer for sorting algorithms where there are colorful bars that will animate when a specific sorting algorithm is triggered by clicking the play button.

To achieve this, I created an array of div elements representing the bars and set their background colors. Additionally, I made another array to keep track of the lengths of the bars so that when I sort the length array, the corresponding bar array gets sorted as well.

 const {bars, setBars} = useContext(BarsContext)
 const [data, setData] = useState([])

  useEffect(() => {
        setData([])
        setBars([])
        for(let i=0; i<=value; i++){
            const randomLength = Math.floor(Math.random() * 500)
            setBars(current => [...current, <div className="bar" ref={ref} style={{ height: randomLength, backgroundColor: "#add8e6" }}></div>])
            setData(data => [...data, randomLength])
        }
    }, [value])

  const runAlgorithm = () => {
        if(active == "bubble"){
            bubbleSort()
        } else if(active == "merge"){
            Mergsort()
        } else if(active == "selection"){
            Selectionsort()
        }
    }
   const sleep = ms => new Promise(r => setTimeout(r, ms));



    const bubbleSort = async() => {
        let count = 0
        console.log(data)
        for(let i=0; i<bars.length; i++){
            for(let j=0; j<bars.length; j++){
            console.log(bars[j].props.style.backgroundColor)
            bars[j].props.style.backgroundColor = "red"
            bars[j+1].props.style.backgroundColor = "red"
              if(data[j] > data[j+1]){
                let temp = data[j+1]
                data[j+1] = data[j]
                data[j] = temp
                setData([...data])

                let temp2 = bars[j+1]
                bars[j+1] = bars[j]
                bars[j] = temp2
                setBars([...bars])
                await sleep(100);
              }
              count +=1
              console.log(count)
            }
          }
          console.log(data)
    }

When implementing the sorting algorithm, I encountered an issue trying to change the background color of the bars to red. Despite logging the properties successfully, an error message indicating undefined props was displayed.

Answer №1

Instead of filling the bars array with DOM elements and expecting them to have certain properties, consider accessing the style property of each DOM element directly.

Furthermore, it may be more efficient to use a data array to render DOM elements with the necessary attributes rather than storing the actual DOM elements in an array.

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

Using ServiceWorker with React and Typescript

If you are working on a javascript-based React project, adding a Service Worker is simply a matter of updating serviceWorker.unregister() to serviceWorker.register() in index.jsx. Here is an example project structure: - src |- index.jsx |- serviceWo ...

Exploring Ajax Testing in React JS with Mocha and Sinon

Is there a way to test an ajax call in a React application? When a click event triggers a method: _search = () => { AppActions.search({ url: this.props.url, queryValue: query }) } This method then calls another method on a store ...

Instructions on how to create a horizontal scrolling div using the mouse scroll wheel

I need help with scrolling a div horizontally using the mouse scroll button. My div does not have a vertical scroll and I would like users to be able to scroll horizontally. Can anyone provide guidance on how to achieve this? ...

What is the process for updating my API data with information submitted through a form?

I am encountering a challenge with my Products component that fetches data from an API endpoint. I also have a Form component where users can input data to update the Products component, displaying both fetched and new data. How can I achieve this? I passe ...

What is the process for generating an Electronic Program Guide for television?

Welcome to the forum! I'm a front-end developer at a company for 6 months now, currently working on a TV app. It's my first experience in this field and I'm facing some challenges, particularly with creating an epg for the app. Unfortunately ...

Get rid of the background shade in the area separating the menu items within a CSS menu

Is there a way to add some spacing between the menu items without affecting the background color applied to the anchor tags? I currently use a right margin of 13px for the spacing, but it also applies the background color, which is not the desired outcome ...

Error: The function rtdb.initStandalone does not exist

As someone who is new to both Node and Firebase, I have encountered an error that doesn't seem to be documented online. The specific error occurs when attempting to load Firebase Database through Firebase Admin: TypeError: rtdb.initStandalone is not ...

Switch between two distinct menus (Reactjs + Material UI)

Recently, I designed a robust menu system that includes a Switcher feature. The concept is straightforward - if the switch is turned off, display the 1st menu; and if it's on, show the second menu. However, there seems to be an issue. When the switch ...

What steps should I follow to integrate Semantic UI into a project using React and Express?

As a newcomer to Semantic/React/Express, I am wondering how to incorporate the stylesheet for Semantic in React. Do I need an html file that directly references the Semantic css and JavaScript files? Currently, I am not utilizing any html files. In my mai ...

Design: Seeking a layout feature where one cell in a row can be larger than the other cells

To better illustrate my goal, refer to this image: Desired Output <\b> Currently, I'm achieving this: current output Imagine 7 rows of data with two columns each. The issue arises in row 1, column 2 where the control needs to span 5 row ...

How to Position an Input Text Beside an Icon Image Using JqueryMobile

Just starting out with jquery mobile and css! Check out my jsfiddle.net/mapsv3/kWJRw/1/, when I use an icon on the left side, the input text gets cut off and I can't see the end of it. ...

React ES6 SystemJS encountered an unforeseen token error that couldn't be caught

Even though I have imported react and react-dom using the System.config setup below, I am still encountering the error mentioned here: Uncaught (in promise) Error: Unexpected token <(…) Here is the HTML structure: <!DOCTYPE html> <html l ...

Tips for using nested flexbox with images

I am facing a straightforward use case where I have an image and a div containing text. The current setting for the div is flex column. My goal is to change the flex setting to row so that the text and image appear side by side. Despite having the corre ...

Creating a text design that spans two lines using Scalable Vector Graphics (SVG

I am working with an SVG that displays strings pulled from an Array... {"label":"Here is an example of the string...", "value":4}, The text above is shown in an SVG element as... <text>Here is an example of the string...<text> I would like ...

Move the material ui menu to the far left side of the page

How can I adjust the menu to align with the left side of the page without any gaps? I've tried various methods but it's not moving to the left. Any suggestions? https://i.sstatic.net/jcAes.jpg Here is the relevant code snippet: <Menu ...

Exploring the potential synergy between the compass and blessings

Currently working on a Compass project and facing the issue of my final CSS output being too large, requiring it to be blessed. I am using Codekit to compile SCSS files but unfortunately, the bless option is not available for Compass projects as mentioned ...

Troubleshooting the Issue with Jquery Menu and Mouse Pointer

Recently, I've been attempting to modify the cursor behavior on a navigation menu that I stumbled upon at HTML Drive's JQuery Menu. I experimented with CSS and jQuery. In my JQuery attempt, I utilized... $("body").hover(function() { $(this).cs ...

What is the method to display HTML code using JavaScript within a span element in a JSP page?

While working on a jsp file, I came across a span tag with the following code: <span id="divBasicSearchResults" style="height:100%;"></span> Below is the Javascript function that generates HTML content for this span: function renderBasicSear ...

The intricacies of the leap search method

Can someone assist me in determining the complexity of the jump search algorithm? I apologize for the additional text required, please disregard it. I really need help with this. void jump_search(Pointeur_L1 P, int length, char * word) { Pointeur_L1 inf, ...

Develop a voice recording feature using ReactJS

In my quest to enhance a chat application with voice recording functionality, I came across the react-mic package. It worked smoothly and provided me with the data needed at the end of the recording session. (link: https://i.stack.imgur.com/nhNCq.png) Now ...