Skip to content

Instantly share code, notes, and snippets.

@julianeon
Created December 12, 2021 01:40
Show Gist options
  • Save julianeon/2bb095c469b28ff6c9257c866bc5cec7 to your computer and use it in GitHub Desktop.
Save julianeon/2bb095c469b28ff6c9257c866bc5cec7 to your computer and use it in GitHub Desktop.
Board clicker in React.
import styled from 'styled-components';
import { useMemo, useState, useEffect, createContext, useContext } from 'react';
const Fleg=styled.div`
display: flex;
`
const Col=styled.div`
display: flex;
justify-content: center;
flex: 1;
background-color: #a57a5a;
text-align: center;
margin-left: 1vw;
margin-right: 1vw;
margin-bottom: 1vh;
`
const palette=["#a57a5a","#9addfb","blue","navy","red","pink","green","yellow","orange","purple","brown","white","gray","black"];
const Color = () => {
const [index,setIndex]=useState(0);
function setColour(value){
let val=(value+1) % (palette.length);
setIndex(val);
}
return (
<>
<Col style={{backgroundColor: palette[index],}} onClick={()=>setColour(index)}><p></p></Col>
</>
)
}
const MakeBoard = ({values}) => {
const [back,setBack]=useState(1);
const size=Math.sqrt(values.length);
let bx=Array.from({ length: Math.ceil(values.length / size) }, (v, i) => values.slice(i * size, i * size + size));
const board = useMemo(() =>
bx.map((item)=> <div style={{backgroundColor: palette[back]}}><Fleg>{item.map((x)=> <Color/>)}</Fleg></div>),
[back]
);
function setBackground(value){
let val=(value+1) % (palette.length);
setBack(val);
}
return (
<>
<div style={{paddingTop: '1vh', backgroundColor: palette[back],}}>
{board}
</div>
<p onClick={()=>setBackground(back)}>.</p>
</>
)
}
function boardgrid(row,col) {
let i=Array.from(Array(row).keys());
let j=Array.from(Array(col).keys());
let xy=i.map((x)=>j.map((y)=>([x,y]))).flat();
return xy;
}
function Board() {
const [values,setValues]=useState(boardgrid(10,10));
return (
<>
<MakeBoard values={values} />
</>
)
}
export default Board;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment