Reputation: 83
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
Upvotes: 3
Views: 4211
Reputation: 732
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>
);
Upvotes: 1
Reputation: 22544
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>
Upvotes: 7