Since I am new to React, I am unable to understand why the below code is not showing the array bars correctly.
After inspecting, I realised that the code is not even generating the 'array-bar' div correctly.
Can somebody help in why this is not working ?
P.S.- This is an array visualiser which visualizes a random array.
import React, { Component } from "react";
import "./SortingViz.css";
export default class SortingViz extends Component {
constructor(props) {
super(props);
this.state = {
array: [],
};
}
componentDidMount() {
this.resetArray();
}
resetArray() {
let array = [];
for (let i = 0; i < 150; i++) {
array.push(randomInt(100,600));
}
this.setState(array);
console.log(array);
}
render() {
const { array } = this.state;
return (
<div className="array-container">
{array.map((value, idx) => {
<div className="array-bar"
key={idx}
style={{ height: `${value}px` }}></div>;
})}
<button onClick={() => this.resetArray}>Generate</button>
</div>
);
}
}
function randomInt(min, max)
{
return Math.floor(Math.random() * (max - min + 1)) + min;
}
Here is the CSS for ref.
.array-container{
margin: 0 auto;
}
.array-bar{
background-color: blue;
width: 5px;
}
You need to return
the div
from the map
callback
render() {
const { array } = this.state;
return (
<div className="array-container">
{array.map((value, idx) => {
return <div className="array-bar"
key={idx}
style={{ height: `${value}px` }}></div>;
})}
<button onClick={() => this.resetArray}>Generate</button>
</div>
);
}