Search code examples
reactjsmappingclosures

Map to a div grid


I am attempting to adapt the following so that 4x4 grid has numbers 1 through n displayed. Each div cell needs an onclick handler.

I tried tinkering the last response from Rendering a chart with colored tiles in React

function App() {
     
  
  return (
    <div style={{
      background: "",
      height: "400px",
      width: "400px",
      display: "flex",
      flexWrap: "wrap"
    }}>
      {new Array(16).fill(1).map(n =>{  return <div style={{
    height: "96px",
    width: "96px",
    backgroundColor: "transparent",
    border: "solid 2px white"
  }}>{n}</div>})}
    </div>
  );
}

export default App;

How to get the numbers 1...16 on each cell? I tried {n} in the div above - didn't help. How to add on click event handler on each div and get the number inside it?


Solution

  • Based on the question. The solution can be obtained with just a few tweaks.

    If you change things as below you will arrive at the solution. Have added comments in the code to highlight the changed portion.

    function App() {
         
      
      return (
        <div style={{
          background: "",
          height: "400px",
          width: "400px",
          display: "flex",
          flexWrap: "wrap"
        }}>
          // Additional map to convert Array fill to the index values instead
          {new Array(16).fill().map((_, i) => i+1).map(n =>{  return <div style={{
        height: "96px",
        width: "96px",
        backgroundColor: "transparent",
        cursor: "pointer", // Showing mouse correctly for click action
        border: "solid 2px white",
      }} onClick={() => console.log(n)}>{n}</div>})} // Added a simple onClick function
        </div>
      );
    }
    
    export default App;
    

    This is just a rough code, I am sure that this code would be part of a larger react app and components should be used to better organize things.