Eric Nguyen
Eric Nguyen

Reputation: 1046

Referencing DOM Elements with React Hooks

I'm creating references to DOM elements in order to use React Hooks for functional components like so:

        let link1, link2 = useRef();

        <ul>
            <li>
               <a ref={element => { link1 = element;}}>FAQ</a>
            </li>
            <li>
               <a ref={element => { link2 = element;}}>Contact Us</a>
            </li>
        </ul>

Question is, do I have to create references for every DOM element I want to target like the above? I feel the code will grow quick.

Here's the codepen for complete code.

Upvotes: 1

Views: 1116

Answers (1)

technicallynick
technicallynick

Reputation: 1592

You could alternatively create one ref for the parent element of all the elements that are related and crawl the node from there.

If you change your schema to:

const ulRef = useRef(null);
<ul ref={ulRef}>
        <li>
           <a className="link">FAQ</a>
        </li>
        <li>
           <a className="link">Contact Us</a>
        </li>
    </ul>

You can crawl the nodes like this:

ulRef.current.children().children('a')

Which should return a nodeList of all of your links. ^This was using a jQuery syntax that is still stuck in my head from years back....

You can use this command to create an HTMLCollection of your li nodes: ulRef.current.children, then iterate over them for the values you are wanting.

I created a simplified example on codesandbox.

Upvotes: 1

Related Questions