How To Change Color Of Specific Elements In Array
I am trying to build a sorting Visualizer using React. Right now, I am implementing BubbleSort. The program looks like this: Here's the code: class Sorter extends Component {
Solution 1:
You can make the colors
array and update the color which was only changed.
classSorterextendsComponent {
state = {
array: [100, 4, 214, 55, 11, 22, 10, 33],
colors: Array(8).fill('blueviolet'), // Array of colors for each bar
};
bubblesorter = async () => {
...
awaitnewPromise((resolve) =>setTimeout(resolve, 100));
// Set different item's color as `red`const colors = arr.map((item, index) => (this.state.array[index] === item ? 'blueviolet' : 'red'));
this.setState({ array: arr, colors });
}
}
};
render() {
const { array, colors } = this.state;
return (
<div><h1>This is a sorter</h1><divclassName='container'>
{array.map((value, id) => (
<span><divclassName='bar'key={id}
// <-Usethecoloratthesameindexoftheitemstyle={{height:value + 'px', backgroundColor:colors[id] }}
></div></span>
))}
</div><buttononClick={this.bubblesorter}>Sort</button></div>
);
}
}
Solution 2:
Tried this...it works but can be improved using modern javascript (not that familiar with it, suggestions welcome)
classSorterextendsComponent {
state = {
array: [],
colors: Array(8).fill('blueviolet'),
}
bubblesorter = async () => {
...
awaitnewPromise(resolve =>setTimeout(resolve, 1000));
const colors = []
for (let k=0; k<8; k++) {
let color = k==j || k==j+1 ? 'red':'blueviolet'
colors[k] = color
}
// console.log(colors)this.setState({ array: arr, colors: colors });
}
}
render()
{
// const array = this.state.arrayconst { array, colors } = this.state;
// console.log(array)return (
<div><h1>This is a sorter</h1><divclassName="container">
{array.map((value, id) => (
<span><divclassName="bar"key={id}style={{height:value + 'px', backgroundColor:colors[id]
}} ></div>
{/* <span>{value}</span> */}
</span>
))}
</div><buttononClick={this.bubblesorter}>Sort</button></div>
)
}
}
Post a Comment for "How To Change Color Of Specific Elements In Array"