0

I am using React-Virtualized.
I would like to setState of AutoSizer width but it gives me warning.

Warning: Cannot update a component (`App`) while rendering a different component (`AutoSizer`). To locate the bad setState() call inside `AutoSizer`, follow the stack trace as described in ....

I understand why it gives me this warning (I am calling setState before the whole
component has finished to be built) but I don't know how to resolve it..

Here is a codesandbox example:
https://codesandbox.io/s/gracious-maxwell-53y2i?file=/src/App.js

Theo Cerutti
  • 779
  • 1
  • 10
  • 33

1 Answers1

1

I found an ugly solution:

import "./styles.css";
import { AutoSizer } from "react-virtualized";
import React, { useEffect, useState, useRef, useCallback } from "react";

export default function App() {
  const [tableWidth, setTableWidth] = useState(0);

  const refCallback = useCallback((ref, width) => {
    if (ref) {
      setTableWidth(width);
    }
  }, []);

  return (
    <div className="App">
      <p>AutoSizer: width = {tableWidth}</p>
      <AutoSizer>
        {({ height, width }) => {
          return <p ref={(ref) => refCallback(ref, width)}>Here another component</p>;
        }}
      </AutoSizer>
    </div>
  );
}

Theo Cerutti
  • 779
  • 1
  • 10
  • 33