Home > Net >  How to access the property of data set?
How to access the property of data set?

Time:01-28

I copied some plain HTML, CSS and JavaScript code from code pen, but as I am trying to convert into React, it says that it can't read properties of null reading (dataset)

JS code:

const wrapper = document.getElementById("wrapper");

const rand = (min, max) => Math.floor(Math.random() * (max - min   1)   min);

const uniqueRand = (min, max, prev) => {
  let next = prev;
  
  while(prev === next) next = rand(min, max);
  
  return next;
}

const combinations = [
  { configuration: 1, roundness: 1 },
  { configuration: 1, roundness: 2 },
  { configuration: 1, roundness: 4 },
  { configuration: 2, roundness: 2 },
  { configuration: 2, roundness: 3 },
  { configuration: 3, roundness: 3 }
];`your text`

let prev = 0;

setInterval(() => {
  const index = uniqueRand(0, combinations.length - 1, prev),
        combination = combinations[index];
  


  wrapper.dataset.configuration = combination.configuration;
  wrapper.dataset.roundness = combination.roundness;
  
  prev = index;
}, 1000);

HTML code for this:

<div id="wrapper"ref={myContainer} data-configuration="1" data-roundness="1">
        <div className="shape"></div>
        <div className="shape"></div>
        <div className="shape"></div>
        <div className="shape"></div>
        <div className="shape"></div>
        <div className="shape"></div>
        <div className="shape"></div>
</div>

I would have attached the CSS, but that is way too long to attach...

I tried using useRef, but that didn't work. I have to find some way to just figure out the work around for this.

Uncaught TypeError: Cannot read properties of null (reading 'dataset')

CodePudding user response:

What very probably happens is that you query the wrapper <div> before it is mounted in DOM, hence your wrapper variable is null, hence the error message.

A very easy workaround would be to simple query the Element just before you need it, inside the setInterval:

setInterval(() => {
  const index = uniqueRand(0, combinations.length - 1, prev),
    combination = combinations[index];

  const wrapper = document.getElementById("wrapper");
  if (wrapper) {
    wrapper.dataset.configuration = combination.configuration;
    wrapper.dataset.roundness = combination.roundness;
  }

  prev = index;
}, 1000);

Demo: https://codepen.io/ghybs/pen/dyjKQGg

  • Related