Get all the children in React

In this article, we will learn how to get all the children in React.

Get all children in React

React, the most popular JavaScript framework out there for frontend development has its own way of selecting the DOM elements.

This is because, React uses JSX (JavaScript XML) as an HTML template, which is basically a JavaScript object representation of the DOM, it is then rendered as the actual DOM by the ReactDom library.

Because we can use the functions as JSX, it gives the flexibility to have custom HTML-like tags and it may or may not have attributes (attributes are converted to properties in JSX by React).

Thus we cannot use the standard, DOM selectors, or Query selectors to get hold of these custom JSX tags, but we have something called the useRef() hook in React, using which we can create a reference to the JSX and access the JSX elements.

import { useEffect, useRef } from "react";

export default function App() {
  const elementRef = useRef();

  useEffect(() => {
    console.log(elementRef.current);
  }, []);

  return (
    <div className="App" ref={elementRef}>
      <h1>Learnersbucket</h1>
    </div>
  );
}

After the component is mounted, the reference to the element is created and if you print the reference, you will see the DOM object of it.

Printing the DOM structure of the React element after creating reference to it with useRef()

For a single element, the reference works best, but what if you have an array of elements? well in that case it becomes a little complex.

It is suggested that you create a unique reference for the element and then loop the element, while that works like a charm, but often cases we don’t have control over the children and we still want to create a reference to them.

In that case, we can have a wrapper over the children, then create the reference to the wrapper and access the children through DOM.

import { useEffect, useRef } from "react";

export default function App() {
  const elementRef = useRef();
  const arr = ['Hello', 'World'];

  useEffect(() => {
    console.log(elementRef.current);
  }, []);

  return (
    <div className="App" ref={elementRef}>
      {arr.map((e) => <Label text={e} key={e} />)}
    </div>
  );
};

const Label = ({text}) => {
  return <span>{text}</span>
}

Accessing all the children of the React element