Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React - How to track useRef children change

I have a component (Comp) that I've added a useRef (compRef) to its parameters. As part of the main useEffect - I'm setting the data of this component. That data contains an array of strings, and the Comp displaying all of them as inputs -

<Comp ref={compRef}>
     <input type="text"/>
</Comp>

and

data = ["HIDDEN", "data1", "data2", "data3", "data4"]

useEffect(() => { 
     compRef.current.refElement.value = data;
}, []);

so now the Comp will look like this -

<Comp>
<generatedWrap> // should be hidden
    <input value="HIDDEN" />
</generatedWrap>

<generatedWrap>
    <input value="data1" />
</generatedWrap>

<generatedWrap>
    <input value="data2" />
</generatedWrap>

<generatedWrap>
    <input value="data3" />
</generatedWrap>

<generatedWrap>
    <input value="data4" />
</generatedWrap>
</Comp>

I want to hide the first input with this hide command -

compRef.current.refElement.children[0].style.display = "none";

The problem is, that with every method (useEffect) I'm using during the mount of the screen, the children are empty. Only after the screen is ready It's working (i.e. triggered by a <button>)

I need a way to track the number of children of the ref before the view is mounted, and once it's greater than 1 to fire the hide command.

How can I do that?

like image 708
Dvi N Avatar asked Oct 27 '22 15:10

Dvi N


1 Answers

Ok

So after a lot of testing - the only option I found is to add setTimeout(() => compRef.current.refElement.children[0].style.display = "none") after the render of the Comp.

(After the render there is still only 1 child but the fact that the setTimeout is a-synchronic make it work)

Thank you all for the help :)

like image 115
Dvi N Avatar answered Nov 10 '22 00:11

Dvi N