Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use array state in React function component?

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!

like image 744
think-serious Avatar asked Oct 20 '25 04:10

think-serious


1 Answers

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]);

like image 107
Hagai Harari Avatar answered Oct 22 '25 19:10

Hagai Harari



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!