Created
January 6, 2023 16:12
-
-
Save timmfin/ffc4cac824e97daa27914ac89ba014ab to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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