Skip to content

Instantly share code, notes, and snippets.

@timmfin
Created January 6, 2023 16:12
Show Gist options
  • Save timmfin/ffc4cac824e97daa27914ac89ba014ab to your computer and use it in GitHub Desktop.
Save timmfin/ffc4cac824e97daa27914ac89ba014ab to your computer and use it in GitHub Desktop.
// In another file as utility function
export function makeRandomColor() {
return /* ... */;
}
// Your partial or module file
function PartialOrModule({ numBoxesToStart = 2 }) {
const serverBoxColors = new Array(numBoxesToStart).fill().map(makeRandomColor);
return <Island module={ManyBoxesIsland} startingBoxColors={serverBoxColors} />
}
// ManyBoxes.jsx (imported ^ with `?island`)
function ManyBoxesIsland({ startingBoxColors }) {
const [numBoxes, setNumBoxes] = useState(startingBoxColors.length);
const addBox = () => {
setNumBoxes(numBoxes + 1)
};
return (
<>
{numBoxes.map((color, i) => {
return <ColorBox startingColor={startingBoxColors[i]} />
})}
<button onClick={addBox}>Add Box</button>
}
</>
);
}
// Separate ColorBox.jsx file
function ColorBox({ startingColor }) {
if (!startingColor) {
startingColor = makeRandomColor();
}
const [color, setColor] = useState(startingColor);
// Adding another handler to regenerate new random box color on click
const onClick = () => {
setColor(makeRandomColor());
}
return (
<div style={{ backgroundColor: color.hex, color: '#fff' }} onClick={onClick}>
{color.value}
</div>
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment