React Basic Hooks - useEffects sample

by dj19910501

HTML

<div id="root"></div>
<div id="other-div"></div>

CSS

body {
  height: 100vh;
  width: 100%;
  font-family: 'Open Sans', sans-serif;
  font-weight: bold;
  font-size: 24px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  text-align: center;
}

#root, #other-div {
  width: 100%;
}

button {
  padding: 10px 20px;
  border: none;
  border-radius: 6px;
  background-color: teal;
  color: white;
  margin: 50px;
  font-weight: bold;
  font-size: 1rem;
}

React

const App = () => {
  return <Board />;
};


const SIZE = 4;
const INITIAL_STATE = Array(SIZE * SIZE).fill(0).map((v, i) => i === SIZE * SIZE - 1 ? "" : i);

const Board = () => {
    const [state, setState] = React.useState(INITIAL_STATE);
    const clickHandler = React.useCallback(index => {
      if (state[index] === "") return;
      let smallerIndex, largerIndex;
      // above
      if (index > SIZE - 1 && state[index - SIZE] === "") {
        smallerIndex = index - Size;
        largerIndex = index;
      }
      // below
      if (index < SIZE * (SIZE - 1) && state[index + SIZE] === "") {
        smallerIndex = index;
        largerIndex = index + SIZE;
      }
      // left
      if (index % SIZE && state[index - 1] === "") {
        smallerIndex = index - 1;
        largerIndex = index;
      }
      // right
      if (index % SIZE < SIZE - 1 && state[index + 1] === "") {
        smallerIndex = index;
        largerIndex = index + 1;
      }
      
      if (smallerIndex !== undefined && largerIndex !== undefined) {
        setState(state => ([
          ...state.slice(0, smallerIndex), 
          state[largerIndex], 
          ...state.slice(smallerIndex + 1, largerIndex),
          state[smallerIndex],
          ...state.slice(largerIndex + 1)
        ]));
      }
    }, [state]);

    const rows = [];
    for (let i = 0; i < SIZE; i++) {
      rows.push( < Row rowIndex = {
          i
        }
        key = {
          i
        }
        state = {
          state
        }
        />);
      }

      return <div className = "board" > {
        rows
      } < /div>;
    };


    const Row = ({
      rowIndex,
      state,
    }) => {
      console.log("23432")
      const cells = [];
      for (let i = 0; i < SIZE; i++) {
        cells.push( <
          Cell key = {
            i
          }
          value = {
            state[rowIndex * SIZE + i]
          }
          index = {
            rowIndex * SIZE + i
          }
          />
        );
 ...