4

I am trying to use an array state for a React functional component.

This is the code I tried.

  const inputLabel = Array(5).fill(React.useRef(null));
  const [labelWidth, setLabelWidth] = React.useState(0);

  React.useEffect(() => {
    inputLabel.map((label, i) => {
      setLabelWidth({...labelWidth, [i]: label.current.offsetWidth});
    });
  }, []);

This is what I tried, but showing an error of React Hook React.useEffect has missing dependencies: 'inputLabel' and 'labelWidth'

Looking for React experts' help. Thanks!

think-serious
  • 1,229
  • 2
  • 12
  • 27

1 Answers1

4

the error you mentioned can be fixed in a few ways - How to fix missing dependency warning when using useEffect React Hook?

but anyhow this isn't supposed to break your app, just to warn you.

in any case, it looks like setLabelWidth called in the effect set LabelWidth as an object, not an array.

to sum up, you don't have to use hooks at all in this case, you can just use { .push() } js array method in a lop


for(let i = 0; i < InputLabel.length ; i++) {
    LabelWidth.push(InputLabel[i])
  }

but if you still wanna do this with hooks and avoid errors I suggest something like that


   const [labelWidth, setLabelWidth] = React.useState([]);

   React.useEffect(() => {
    if (labelWidth.length === 0) {
     const inputLabel = Array(5).fill(React.useRef(null));
     inputLabel.map((label) => {
     setLabelWidth([ ...labelWidth, label.current.offsetWidth ]);
     }
    });
   }, [labelWidth, setLabelWidth]);

Hagai Harari
  • 2,767
  • 3
  • 11
  • 23