Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

reactjs get the children count of an element

Tags:

reactjs

im trying to get the count of child elements inside the 'container' div.

let ElementRef = useRef()

    useEffect(() => {
        let Elementcount = ElementRef.childNodes.length
        console.log(Elementcount)
    })
    
    return (
       <div className='container' ref={ElementRef}>
         <p>paragraph one</p>
         <p>paragraph two</p>
         <p>paragraph three</p>
       </div>
    )

desired outcome in the console:

3

but im getting this error: TypeError: Cannot read property 'length' of undefined

like image 285
abood alwa7sh Avatar asked Feb 02 '26 03:02

abood alwa7sh


2 Answers

You need to use .current property to access your ref.

useRef returns a mutable ref object whose .current property is initialized to the passed argument (initialValue)

const { useRef, useEffect } = React;

const App = () => {
  const ElementRef = useRef(null)

  useEffect(() => {
      const Elementcount = ElementRef.current.childNodes.length
      console.log(Elementcount)
  })

  return (
     <div className='container' ref={ElementRef}>
       <p>paragraph one</p>
       <p>paragraph two</p>
       <p>paragraph three</p>
     </div>
  )
}

ReactDOM.render(
  <App />,
  document.getElementById("root")
)
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.1/umd/react-dom.production.min.js"></script>
<div id="root"></div>
like image 71
Hassan Imam Avatar answered Feb 03 '26 20:02

Hassan Imam


When you define a useRef, you must use .current to get the current value. Change the code as follows

let ElementRef = useRef();
  useEffect(() => {
    let Elementcount = ElementRef.current.childNodes.length;
    console.log(Elementcount)
});
  return (
    <div className='container' ref={ElementRef}>
         <p>paragraph one</p>
         <p>paragraph two</p>
         <p>paragraph three</p>
       </div>
  );
like image 36
RABI Avatar answered Feb 03 '26 19:02

RABI



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!