Reputation: 223
I want to create a board with colored squares. The point is that I want to have an array with for example 4 colors and I need to fill every square with random color from that array.
Right now I generate n random colors (colors.js file)
export const randomUpTo = (max) => {
return Math.floor(Math.random() * max);
};
const randomColor = () => {
const r = randomUpTo(255);
const g = randomUpTo(255);
const b = randomUpTo(255);
return `rgb(${r}, ${g}, ${b})`;
};
export const generateColors = (n) => {
return Array.from(new Array(n), randomColor);
};
...and I display n different sqaures in Board.js component:
import React, { Component } from "react";
import { generateColors } from "../../utils/colors";
import "./Board.css";
class Board extends Component {
state = {
colors: generateColors(12)
};
render() {
const { colors } = this.state;
const squares = colors.map((color, index) => {
return (
<div key={index} className="square" style={{ background: color }}></div>
);
});
return <div className="squares">{squares}</div>;
}
}
export default Board;
but it's wrong because I create n (12 in this case) squares and fill them with n (12 in this case) colors. I need to have an array of colors (for example colors = [black, white, blue, green]) and fill n squares (12 in this case) with random color from this array.
Upvotes: 1
Views: 3112
Reputation: 41893
The colors
is an array of colors, not a single color. So you would have to get the particular color e.g. by index.
const squares = colors.map((color, index) => {
const color = colors[Math.floor(Math.random() * 4)];
// or dynamically * colors.length
return (
<div key={index} className="square" style={{ background: color }}></div>
);
});
Upvotes: 2