Skip to content

Instantly share code, notes, and snippets.

@josno
Last active September 24, 2020 15:36
Show Gist options
  • Select an option

  • Save josno/b61b79ba01461c381ac93f41a6550570 to your computer and use it in GitHub Desktop.

Select an option

Save josno/b61b79ba01461c381ac93f41a6550570 to your computer and use it in GitHub Desktop.
ColorComponent
import React, { useState, useEffect } from "react";
import styled from "styled-components";
const colorList = ["#FFBE0B", "#FB5607", "#FF006E", "#8338EC", "#3A86FF"];
const ColorParent = () => {
const [randomList, setRandomList] = useState([]);
const [update, setUpdate] = useState(true);
const randomize = (list) => {
//Declare an empty list that will fill up with the random colors
let randomizedList = [];
//Let's say I want to get an array with 5 different colors
for (let i = 1; randomizedList.length < 5; i++) {
//Get a random index based within the list argument's length
let newRandIndex = Math.floor(Math.random() * list.length);
//If my new list already has the value of the random index, get another color
if (randomizedList.includes(list[newRandIndex])) {
newRandIndex = Math.floor(Math.random() * list.length);
} else {
//If it's a color that is not on the list yet, push it to the new list
randomizedList.push(list[newRandIndex]);
}
}
//Set the generated list to the state
setRandomList([...randomizedList]);
};
useEffect(() => {
if (update) {
randomize(colorList);
setUpdate(false);
}
}, [update]);
const listOfColors = randomList.map((color, index) => {
return <ColorChild color={color} key={index} />;
});
return (
<div>
{listOfColors}
<button
style={{ display: "block", margin: "0 auto" }}
onClick={() => setUpdate(true)}
>
Reshuffle Colors
</button>
</div>
);
};
const /*This is the child component receiving the color prop ===> */ ColorChild = ({ color }) => {
/*This is also another component (for style) so pass the color prop again ===> */
return <ColorItem color={color}></ColorItem>;
};
const ColorItem = styled.div`
height: 100px;
width: 100px;
display: inline-block;
//The color prop is now being used below
background-color: ${(props) => (props.color ? props.color : "purple")};
`;
export default ColorParent;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment