Using useEffect does not update DOM element

Viewed 38

I am trying to set a role attribute of an element, when I console.log it seems that the attribute is changed, however when I inspect the DOM the table role isn't updated and I can't figure out why.

What am I doing wrong here and how can I update the role attribute in the DOM properly?

Here is my code:

import React, { useEffect } from 'react';
import * as ReactDOM from 'react-dom';
import { Grid, GridColumn } from '@progress/kendo-react-grid';
import products from './products.json';

const App = () => {
  useEffect(() => {
    let table = document.getElementsByClassName('grid')[0];
    table.setAttribute('role', 'table');
    console.log(table);
  }, []);
  return (
    <Grid
      style={{
        height: '400px',
      }}
      data={products}
      className="grid"
    >
      <GridColumn field="ProductID" title="ID" width="40px" />
      <GridColumn field="ProductName" title="Name" width="250px" />
      <GridColumn field="Category.CategoryName" title="CategoryName" />
      <GridColumn field="UnitPrice" title="Price" />
      <GridColumn field="UnitsInStock" title="In stock" />
    </Grid>
  );
};

ReactDOM.render(<App />, document.querySelector('my-app'));
1 Answers

You are setting the role attribute on the first .grid element which a HTMLDivElement.

Do this instead:

const grid = document.getElementsByClassName('grid')[0];
const table = grid.querySelector("table")
table && table.setAttribute('role', 'table');

Full code

import  React, { useEffect }  from 'react';
import * as ReactDOM from 'react-dom';
import { Grid, GridColumn } from '@progress/kendo-react-grid';
import products from './products.json';

const App = () => {
  useEffect(() => {
    const grid = document.getElementsByClassName('grid')[0];
    const table = grid.querySelector("table")
    table && table.setAttribute('role', 'table');
    console.log(table); 
  }, []);


  return <Grid  className="grid" style={{
    height: '400px'
  }} data={products}>
        <GridColumn field="ProductID" title="ID" width="40px" />
        <GridColumn field="ProductName" title="Name" width="250px" />
        <GridColumn field="Category.CategoryName" title="CategoryName" />
        <GridColumn field="UnitPrice" title="Price" />
        <GridColumn field="UnitsInStock" title="In stock" />
      </Grid>;
};

ReactDOM.render(<App />, document.querySelector('my-app'));
Related