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?
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
You can also use window.document.querySelectorAll within react to access any component you wish.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With