TransWikia.com

react ref and query selector all

Stack Overflow Asked by peter flanagan on February 10, 2021

I am using react and useRef

Previously I was checking the rows of a table using the following:

const rows = document.querySelectorAll('table tr');

But now I have multiple tables on my page so I need to use a ref to ensure I target the correct table.

When I try and use the ref I get the following error:

Failed to execute ‘querySelectorAll’ on ‘Document’: ‘[object
HTMLTableElement] tr’ is not a valid selector.

My code looks like the following:

const App = () => {

   const tableRef = React.useRef(null);

   const someMethod = () => {
      // this gives the error specified above
      const rows = document.querySelectorAll(`${testRef.current} tr`);

   }

   return (
     <>
       <table ref={tableRef}>
          //code here
        </table>
        <button onClick={() => someMethod()}>Random Button</button>
     </>
   )
}

Can anyone advise how to correctly target the ref in document.querySelectorAll?

2 Answers

You can also use window.document.querySelectorAll within react to access any component you wish.

Answered by Diego Fortes on February 10, 2021

ref.current is a DOM node (or null). So you need

const rows = testRef.current.querySelectorAll('tr');

Also you could use testRef.current.rows to access rows. MDN

Answered by Yury Tarabanko on February 10, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP