React: How to view children nodes with useRef?

wongz

How can I look at the properties available inside the children of a ref?

I'm trying to ultimately traverse the children nodes.

As a first step, what is the syntax to view the [object HTMLCollection]? As a second step, how can I map through each child?

export default function App() {
  const ref = React.useRef();

  React.useLayoutEffect(()=>{
    /** Attempts to view the nodes aren't working */

    console.log(ref.current.children); // [object HTMLCollection]
    console.log(React.Children.toArray(ref.current.children)); // Error: Minified React error #31
    console.log(ref.current.children[0]); // [object HTMLDivElement]
    console.log(JSON.stringify(ref.current.children[0])); // Error: "Converting circular struture to JSON"


    /** Attempts to map through the nodes aren't working*/

    // Error: "ref.current.children.forEach" is not a function
    ref.current.children.forEach(child => {
      console.log('child', child);
    });

    // Error: "ref.current.children.map" is not a function
    ref.current.children.map((child) => {
      return console.log('child', child);
    });

    // Error: Minified React error #31
    React.Children.map(ref.current.children, (child) => {
      return console.log('child', child);
    });
  }, [ref]);

  return (
    <View 
    ref={ref}>
      <View></View>
      <View></View>
      <View>
        <Pressable>
          <Text>I want this text</Text>
        </Pressable>
      </View>
    </View>
  );
}

Expo Snack

Spankied

Nodelist doesn't have map method. It is an iterable though, so you an spread it into an array though.

[...ref.current.children].map((child) => {
    return console.log("child", child);
});

Or

Array.from(ref.current.children)

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related