Search code examples
reactjsreact-hooksref

How to create Ref for a div in two dimensional loop


Here I am trying to pass the ref attribute to div but it is not happening, can anybody help me in resolving this issue


 const ref = useRef<HTMLDivElement>(null);

 for (let curRow = 1; curRow <= props.row; curRow++) {
    for (let curCol = 1; curCol <= props.col; curCol++) {
      columns.push(
        <div
          ref={ref}
          style={{ minWidth: `${minWidth}px` }}
          className="el1"
          id={`${curRow}${curCol}}`}
          key={`${curRow}${curCol}${generateKey(curCol)}`}
        >{`${curRow}${curCol}`}</div>
      );
    }
  }```

Solution

  • If you want refs to all the divs, then you can't use a single ref, you need an array of them, or a 2d array of them. For example:

    const refs = useRef<(HTMLDivElement | null)[][]>([]);
    
    for (let curRow = 0; curRow < props.row; curRow++) {
      for (let curCol = 0; curCol < props.col; curCol++) {
        columns.push(
          <div
            ref={(el) => {
              refs.current[currRow] = refs.current[currRow] || [];
              refs.current[currRow][currCol] = el;
            }}
            style={{ minWidth: `${minWidth}px` }}
            className="el1"
            id={`${curRow}${curCol}}`}
            key={`${curRow}${curCol}${generateKey(curCol)}`}
          >{`${curRow}${curCol}`}</div>
        );
      }
    }
    
    // used like:
    useEffect(() => {
      console.log("Element at zero/zero: ", refs.current[0][0]);
    }, []);