What is the best way to retrieve information from a data set?

After borrowing some basic HTML, CSS, and JavaScript code from CodePen, I ran into an issue while attempting to convert it to React. The error message says that it cannot read properties of null (specifically 'dataset').

Here is the JavaScript code snippet:

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 }
];

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);

And here's the corresponding HTML code:

<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>

Uploading the associated CSS would be too lengthy...

I attempted using useRef, but didn't have any luck. Time to find a workaround for this roadblock.

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

Answer №1

It is likely that you are querying the wrapper <div> before it is fully mounted in the DOM, causing your wrapper variable to be null, resulting in an error message.

An easy workaround would be to query the Element right before you need it, within 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);

Check out the demo: https://codepen.io/ghybs/pen/dyjKQGg

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What's the deal with $routeProvider in angularJS?

I'm having some trouble with my simple web app that I'm trying to update using route provider. Everything works fine when I click on the list items on the page, but when I refresh the page, I get a 404 error. It seems like it's trying to acc ...

Combining Objects in an Array using Node.js: A Step-by-Step Guide

I am working with Node.js and have 3 different sets of data. The first set contains: [ { "userId":"54c7f3ef-64d4-40de-8100-d2ec81e8aaf3", "dailyData":159392.235451, "dailyDataInUSC":255.28 ...

What is the method for generating a custom tag (similar to a class) within an option contained in a SELECT element?

I need to create a select box with two options: cars or boats. Here is my initial idea: <select> <option value="1" class="cars">Car1</option> <option value="2" class="boats">Boat1</option> <option value="3" class="ca ...

Executing Ionic function before application shutdown

Does anyone know of a function that can be triggered when the app is about to exit, close, or go into the background? Essentially any event that indicates "the user has stopped using the app"? In my app, I create a 'user log' that keeps track of ...

The node version displayed in the terminal doesn't match the one indicated by the command "node -v"

When initiating a fresh React application (e.g. npx create-react-app ecommerce), I encounter an issue where it indicates that I am using Node 12.22.1 while Create React App needs Node 14 or above. Interestingly, when I check my Node version with node -v ...

Is there a comparable Javascript alternative to the Ruby gem "site_prism" for Page Objects design?

Is there a JavaScript framework for Protractor in NodeJS that provides a clean way to define Page Object Elements similar to site_prism? I've explored astrolabe but it doesn't quite meet the requirements. This is an example of how Page Objects a ...

Modify an element upon clicking the mouse on an image

I am looking to dynamically change the paragraph element with className="details" to an editable input field when a user clicks on the image with className="edit-icon" within the same grid container. How can I achieve this functionality ...

Is there a way to log and process div data posted using jQuery in CSS format?

I am looking to extract and log a JavaScript-calculated result from an anonymous survey created using a WordPress plugin. The generated HTML code is: <div ref="fieldname57_1" class="cff-summary-item"> <span class="summary-field-title cff-summary ...

AngularJS is failing to recognize the onload event when loading a URL

I am currently working with the AngularJS Framework and I have encountered an issue. My directive only seems to work when the window is fully loaded. screensCreators.directive('createscreen', function () { return { restrict: "A", ...

Guide on how to retrieve the vertex information once an object is loaded using the ObjLoader in Three.js

When using ObjLoader in Three.js to load a *.obj file into my scene, everything works fine. However, I'm uncertain on how to manipulate the object's vertices and indices individually. How can I access the vertices of the loaded *.obj model? Atte ...

Attempting to arrange a line consisting of four individual cells

I am facing an issue while trying to create a row with 4 cells and I can't figure out why it's not working. The structure involves a parent element called row with 4 child elements. <div className='row'> <div ...

Tips for keeping the header section anchored to the top of the page

I am having trouble getting the menu bar and logo to stick at the top of my header section in the template. I have been trying different solutions, including using the sticky.js plugin for almost 4 days now but it's not working. I also have parallax e ...

Click to add a different template into the document

My HTML page consists of a form with multiple input fields and a carousel. Towards the bottom of the form, there is a button labeled Add another quote. This button essentially duplicates the input fields above (all contained within class="quote"). Here&ap ...

Troubleshoot: Border problem within nested columns in Bootstrap

https://i.sstatic.net/RDWfp.png My layout is based on the bootstrap 4 grid system, as shown in the image above. The problem I'm facing is that the border at the bottom row is misaligned. I have four nested columns in the first and second rows, but on ...

Incorporating Typescript with Chart.js: The 'interaction.mode' types do not match between these two entities

I am working on developing a React Functional Component using Typescript that showcases a chart created with chartjs. The data and options are passed from the parent component to the child component responsible for rendering the line chart. During the pr ...

"Implementing conditional styling in React with Material-UI and custom

Is there a way to adjust the border radius of a card based on the proximity of the Typography element? Ideally, I would like the border radius of the card to be set to borderRadius: '4px 4px 4px 4px !important' when the Typography is close. < ...

Having trouble with redundant code while updating state in ReactJS - React JS

Currently, I am working on a prayer times web app using reactJS (nextjs). To achieve this, I first fetch the geolocation coordinates and then retrieve the city and country name based on these coordinates. Following that, I obtain the prayer times for the s ...

Cross-browser compatibility issues preventing CSS button effects from functioning properly

Experiencing some challenges with CSS Button effects not functioning consistently across different browsers. The display is satisfactory in Chrome, but not in Firefox. Struggling to pinpoint the source of the issue. Here is my current setup: Fiddle a ...

A guide on adding the !important rule using the useStyles hook in @material-ui

I'm currently working on a card component with metrial-ui. I need help with applying "!important" using metrial-ui and UseStyles in react.js, particularly for properties like width or height when the value is a number. To provide more conte ...

Retrieve Django imagefield file name using jQuery before submitting

Exploring the essential Django image file upload procedure, where the image model incorporates the ImageField class. There's a custom display button replacing the default upload button which usually showcases the image name alongside it. Hence, the ne ...