Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The current of React UseRef is both the initial value and the element that I'm expecting

Tags:

reactjs

I'm trying to use the useRef hook to set the ref of a div but it seems as if the value doesn't update once the ref is found. How is the below possible?

current is both 0 AND div

    const SelectDropDown = props => {
    const { helperText, label, ...restProps } = props;
    const [animals, setAnimals] = React.useState('');
    const labelRef = useRef(0);

    const handleChange = event => {
      setAnimals(event.target.value);
    };

     console.log('ref', labelRef);

   return (
   <FormControl>
      <div ref={labelRef}></div>
     <InputLabel id={`label-${label}`}>Animals</InputLabel>
        <MSelect
        autoWidth
        labelId={`label-${label}`}
        id="demo-simple-select"
        value={animals}
        onChange={handleChange}
        >
        {options.map(option => {
         return <MenuItem value={option.id}>{option.value}</MenuItem>;
         })}
         </MSelect>
        </FormControl>
      );
   };
like image 246
insivika Avatar asked Oct 27 '25 05:10

insivika


1 Answers

the ref isn't assigned and therefore not properly accessible until the component has fully mounted. I ended up using useEffect to get the value.

like image 115
insivika Avatar answered Oct 28 '25 19:10

insivika



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!