How can I update the style of my array-bars using componentDidMount()?

I created a visualization tool for sorting algorithms that displays vertical bars with varying heights and sorts them. The "Generate new Array" button triggers a function to generate a new array each time it's clicked, which is also used in the componentDidMount() function. How can I change the style property of these bars when the button is clicked? I attempted to select all elements with the class name 'array-bars', store them in an array, and then loop through to change their style properties, but it was unsuccessful. Here is the relevant code snippet:

{ // 'array' is a constant array storing numbers; it's the only state of this program.
  array.map((value, idx) => (
    <div
      className="array-bar"
      key={idx}
      style={{ height: value, backgroundColor: 'turquoise' }}></div>))
}

componentDidMount(){
  this.resetArray();
}

// This function is called when 'generate new array' button is clicked    
resetArray(){
  const array = [];
  for (let i = 0; i < 300; i++) {
    array.push(randomIntFromInterval(15, 650));
  }
  const arrayBars = document.getElementByClassName('array-bar');
  for (let i = 0; i < arrayBars.length; i++)
    arrayBars[i].style.backgroundColor = 'green'; //this is failing

  this.setState({ array });
}

Edited: Below is the function where I successfully changed the style properties using the method outlined in the previous section. Also, I need assistance on how to change colors during the mergeSort() function at the end of the code snippet. Using this.setState() at the end alters the color at the beginning only.

 mergeSort(){
         for(let i=0;i<animations.length;i++){
             const arrayBars= document.getElementsByClassName('array-bar');
             const colorChange=i%3!==2;
             if(colorChange){
                 const [barOne,barTwo] =animations[i];
                 const barOneStyle=arrayBars[barOne].style;
                 const barTwoStyle=arrayBars[barTwo].style;
                 const color=i%3===0?'red':'turquoise';
                 setTimeout(()=>{
                    barOneStyle.backgroundColor=color;
                    barTwoStyle.backgroudColor=color;
                 },i*2);
             }
             else{
                 setTimeout(()=>{
                    const[barOne,newHeight]=animations[i];
                    const barOneStyle=arrayBars[barOne].style;
                    barOneStyle.height=newHeight+'px';
                 },i*2)
             }
         }
    }

Answer №1

When working with React, it's essential to leverage the power of state changes to drive actions within your application. One approach is to establish an initial state that includes the starting background color and then update this value as necessary. UPDATE: To trigger specific actions upon a button click event, simply assign the button's onclick attribute to a function of your choice. In this example, a button is added with its onclick attribute pointing to resetArrays.

class YourComponent extends React.Component {
  constructor(props){
    super(props);
    this.state = {
      barBg: 'turquoise'
    }
  }

  render(){
    return <div>
     <button onClick={this.resetArray.bind(this)}>Generate new array</button>
     { //array is const storing array of numbers which is also only state of this program.
      array.map((value, idx) => (
        <div
         className="array-bar"
         key={idx}
         style={{ height: value, backgroundColor: this.state.barBg }}></div>))
      }
     </div>
  }

  componentDidMount(){
    this.resetArray();
  }

  // this is called when I click generate new array    
  resetArray(){
    const array = [];
    for (let i = 0; i < 300; i++) {
      array.push(randomIntFromInterval(15, 650));
    }

    this.setState({ array, barBg: 'green' });
  }
}

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

Ensuring the website retains the user's chosen theme upon reloading

I have been developing a ToDo App using MongoDB, EJS, and Node JS. My current challenge involves implementing a theme changer button that successfully changes colors when clicked. However, whenever a new item is added to the database, the page reloads caus ...

Guide on implementing a looping settimeout function on a sliding page to dynamically load an HTML template within the Framework 7 framework

My current setup involves using Framework7 (framework7.io). The code below functions correctly on the main view page, utilizing a looping settimeout to refresh signups.html every second: <script type=“text/javascript” src=“code.jquery.com/jquery- ...

Capturing Vuejs data for various pathways

Currently, I am developing a Vue file that contains the following code: <router-link :to="{name: 'detailed'}" tag='li' @click='getData("test")'> testing</router-link> In the script section, the code looks like th ...

Generating a tree structure using a JavaScript array

Looking to build a tree structure from a given list of data where the paths are represented like: A-->B-->C-->D-->E.. A-->B-->C-->D-->F.. A-->F-->C-->D-->E.. . . . All possible data paths are stored in an array. The de ...

Ran into a situation where two kids had identical keys: `function v4(options, buf, offset)`

import {v4 as uuidv4} from "uuid" <div ref={scrollRef} key={uuidv4}> <div className={`message ${message.fromSelf ? "sended" : "received"}`}> <div className="content"> <p>{message.message}</p> ...

Is the Angular Karma test failing to update the class properties with the method?

I am struggling to comprehend why my test is not passing. Snapshot of the Class: export class Viewer implements OnChanges { // ... selectedTimePeriod: number; timePeriods = [20, 30, 40]; constructor( /* ... */) { this.selectLa ...

Combining AngularJS with Servlets: A Seamless Integration

I am attempting to retrieve a JSON object from a servlet by calling a function through a link in my HTML code. Below is the HTML link that calls the fTest function: <td><a href="" ng-controller="minaplantaCtrl" ng-click="fTest(x.id_camion_descar ...

implementing toggle functionality for an array of items in ReactJS

I have an array and I am trying to create a show/hide feature for each item based on toggling. When I click on one item, it should expand while simultaneously hiding the previously expanded item. Here is the code snippet I have been working on: class App e ...

Updating the key within an array of objects

In my array of objects, I have the following data: arrayOfObject = [{'key1': [1,2]} , {'key2': [1,2,3]} , {'key3': [1,2,4]}] I know the name of the key that I want to replace in my array : var keyString = 'key1&apos ...

Encountering issues with React webpack build process

I'm currently working on my first React app and encountering an issue with my package.json file. I'm puzzled as to why this is happening. It seems that the problem lies in the --output section of my code, even though I'm following a tutorial ...

Unpacking JSON Objects in Typescript: Working with Private Variables

I have a TypeScript model object called user export class User { constructor( private _name: string, private _email: string ) {} public get name():string { return this._name; } public set name(value:string) { this._name = value; } g ...

Receive the height from the parent element using the box-sizing property set to border-box

Let's talk about a CSS challenge. .parent{box-sizing: border-box; height: 60px; border: 1px solid green;} The child div has its own styling: .child{height:inherit;background: red} Here is the code snippet: ...

Exploring ways to customize the date display in chart.js

Need help with adjusting the date display on my chart? See the chart below: https://i.sstatic.net/aHJtw.png Is there a way to customize how dates are displayed, like showing them horizontally and only every third date? Check out my code snippet below: ...

"Learn the steps to toggle a sub menu using an onclick event and how to hide it using another

I created a sidebar navigation that displays submenus on mouseover, but I want them to open on click and close when clicking on the same tab. Please take a look at my code on this CodePen link. Thank you. <nav class="navigation"> <ul class="mai ...

Transferring information between Express and React through the Contentful API

I have embarked on a journey to explore Contentful's headless CMS, but I am encountering a challenge with their API client. My goal is to combine Express with React for server-side rendering, and I am utilizing this repository as my starting point. S ...

JavaScript code does not seem to be functioning properly on my computer, but it works perfectly fine on

While the code functions perfectly in JSFiddle, it seems to fail when I try to implement it in an HTML file. Despite my efforts, I am unable to pinpoint the source of the issue. If you'd like to view the working version, here is the Fiddle demo. Bel ...

Crafting a custom URL using axios that incorporates a parameter with the special character "&" in it

Currently, I am working on a project involving axios.get and the URL structure is as follows: http://example.com/path?element1={example1}&element2={example2}&element3={function(query)} function ((condition1: string, condition2: string) => { q ...

Guide on adding the .html extension to your URL in Nextjs

In my Nextjs 13.5.2 page directory setup, I am facing a requirement to add ".html" to the URL for SEO purposes on Baidu. For instance: www.test.com/news/123 -> www.test.com/news/123.html I have attempted the following: Renaming the filename to [slug] ...

What is the proper way to invoke a function in the code-behind using JavaScript?

I need to invoke a function in the code behind from JavaScript Button : <button class = "btn btn-outline btn-danger dim" type = "button" onclick = "confirmDelete ()"> <i class = "fa fa-trash"> </i> ...

Execute function prior to redirection of iframe

I have a specific challenge with an iframe on my webpage. I am looking to trigger a function right before the iframe reloads a new page, rather than after it has finished loading. I need this function to be triggered before the iframe redirects to the new ...