Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

react ref and query selector all

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?

like image 599
peter flanagan Avatar asked Nov 30 '22 08:11

peter flanagan


2 Answers

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

like image 117
Yury Tarabanko Avatar answered Dec 04 '22 07:12

Yury Tarabanko


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

like image 22
Diego Fortes Avatar answered Dec 04 '22 07:12

Diego Fortes