Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

176
Visualizações
React useRef returning null after running a useEffect to fill the initial state

I am attempting to hook my custom component to a ref using react's useRef in order to use html2canvas and render the element to a canvas.

const dataLetters = {
  headers: [
    'A',
    'B',
    'C',
    'D',
    'E',
    'F',
    'G'
  ],
  rows: [
    ['A', 'B', 'C', 'D', 'E', 'F', 'G'],
  ]
};

export default function LettersPage() {
  // refs
  const LettersTableRef = useRef(null);

  useEffect(() => {
    console.log('letter ref');
    console.log(LettersTableRef.current); // same result when logging LettersTableRef
  }, [LettersTableRef]);

  return (
    <Page>
      <CustomizedTable ref={LettersTableRef} data={dataLetters } />
    </Page>
  );
}

However, this code when I run it, the console logs null after logging "letter ref". The CustomizedTable simply takes the data and builds rows and a header given the information - nothing fancier.

I am new to React and javascript. I have read I can in javascript give an element an id - I don't know how to do that in a react context, and am trying to stick to the practice of using React within React instead of plain js.

Please let me know what I am doing wrong!

-----Updated to add the code for CustomizeTable----

import Table from '@mui/material/Table';
import TableBody from '@mui/material/TableBody';
import TableCell, { tableCellClasses } from '@mui/material/TableCell';
import TableContainer from '@mui/material/TableContainer';
import TableHead from '@mui/material/TableHead';
import TableRow from '@mui/material/TableRow';

export default function CustomizedTables({ data, id }) {
  return (
    <TableContainer>
      <Table>
        <TableHead>
          <TableRow>
            {data.headers.map((header) => (
              <TableCell>{header}</TableCell>
            ))}
          </TableRow>
        </TableHead>
        <TableBody>
          {data.rows.map((row) => (
            <TableRow>
              {row.map((datum) => (
                <TableCell>{datum}</TableCell>
              ))}
            </TableRow>
          ))}
        </TableBody>
      </Table>
    </TableContainer>
  );
}
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You should check again on your browser's console. There should be some errors regarding ref and each child in a list should have a unique key...

Using refs is an advanced topic in React and you basically get a pointer to an object. This will work with references to class-components or HTML-elements but is not directly working with function components. For this you have to use forwardRef to wrap your function component inside.

I've fixed your code here: https://codesandbox.io/s/vigorous-dew-u2bm9?file=/src/CustomizedTable.jsx

With forwardRef you can set the reference to any child element so the outer component can directly access it with useRef. There are some other ways to get methods as reference with useImperativeHandle but this will be even more advanced.

const CustomizedTables = forwardRef(({ data, id }, ref) => (
    <TableContainer ref={ref}>
      ....
    </TableContainer>
));

I can strongly recommend the official documentation on this topic: https://reactjs.org/docs/hooks-reference.html

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda