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

Troubleshooting peerDependencies issue in Laravel 9 while installing ReactJS and VueJS with laravel/ui

I added Laravel/Ui to a Fresh Laravel 9 installation for setting up ReactJs I followed these commands step by step in the command line interface: composer require laravel/ui php artisan ui react npm install After running the npm install command, I en ...

Loss of image quality when utilizing Next/Image in NEXT JS

I am currently developing a web application using Next.js 13, and I recently noticed a decrease in the quality of my images. I'm not sure what went wrong or what I may have missed. Upon inspecting the HTML element on the browser, I found this code: & ...

How to properly import and use a MaterialUI theme from a separate file

Hey there, I'm currently exploring MaterialUI and React. One thing I'm attempting to do is import a theme from another file and toggle between themes using a switch in MaterialUI. To accomplish this, I've created a Layout component that will ...

Height problem with the data-reactroot component

On one of my web pages, there is a data-reactroot element with a height of approximately 1906px. However, the surrounding divs and html tags have a height of only 915px. I am trying to figure out how to make all the enclosing elements match the same heigh ...

Guide to implementing a scrollable grid layout using Material-UI

Currently, I am trying to create an auditorium viewer and seat selector screen using Material-UI. However, I have not been able to find a similar control for this specific task. Do you have any suggestions on how I could go about implementing this screen? ...

React App not functioning properly with http-proxy-middleware

After setting up proxies on my create-react-app application with http-proxy-middleware, I'm encountering a persistent 404 error whenever I click the relevant link. Following the setup instructions meticulously, I still can't seem to resolve this ...

What is the best way to deploy a nodejs expressjs application to a server?

I have successfully developed a nodejs and express application that works perfectly on my localhost. To start the application, I simply run the command npm start or node index.js. Recently, I uploaded all the necessary files, including node_modules, to a ...

Invoking a parent controller method from a directive in AngularJS

I have utilized a tree grid plugin from the following link: https://github.com/khan4019/tree-grid-directive and I made some customizations to its template: .directive('treeGrid', [ '$timeout', function($timeout) { return { ...

Enhancing Line Graphs in React Recharts: Implementing Filters for Improved Visualization

Within my Next.js application, I am working on integrating the recharts library from . My goal is to add a filter option to the charts for timeframes such as 1 day, 1 week, and 1 month. How can I customize the graph to include this feature? Alternatively, ...

Show button once modal has been closed

I have a 'start' button that triggers a modal window with an embedded video. Once the user closes the modal, I want to show a 'redeem' button after a delay of 6 seconds. HTML: <a id="video-start" onclick="openVideoModal()"><i ...

"Encountering problems with location search function on Instagram API for retrieving posts

I've been working on integrating two APIs – Instagram and Google Maps. While I've managed to get everything functioning smoothly, there's an issue with displaying "up to 20 pictures" around a specific location. I'm unsure why this in ...

What is the best method to ensure that an image remains at the bottom of a div even as the div's height adjusts?

In my current project, I am facing a challenge with positioning an image in the bottom-right corner of a dynamically changing div. Initially, this is easily achieved by using CSS selectors: #div1 { position: relative; } #div1 img { position: abso ...

Creating GraphQL from a Mongoose model: A step-by-step guide

I'm currently utilizing graphql and mongodb to add a specific object to the database. While using the same method to add an object, this particular one has a nested structure. package.json { "name": "workplaces", "versi ...

Is there a problem connecting to the MongoDB server?

I am having trouble connecting to the MongoDB server using the link provided below. I have double-checked the password and dbName, but it still won't connect. Can someone please assist me with this? const mongoose = require('mongoose'); ...

The jQuery autocomplete feature seems to be malfunctioning as no suggestions are showing up when

I am currently generating input text using $.each: $.each(results, function (key, value) { if (typeof value.baseOrSchedStartList[i] != 'undefined') { html += "<td><input type='te ...

Is it better to dynamically generate HTML elements or to just directly paste complete fragments in the code?

After manipulating the DOM and injecting AJAX content, I often find myself filling in the new content into a copied HTML fragment, then populating it with the updated information before using $().html() to insert the modified code back into the DOM. The ex ...

Replicate the anchor's functionality (opening in a new window when 'ctl' is pressed) when submitting a form

I have a question that may seem unconventional - Is there a graceful method to replicate the functionality of an anchor tag when submitting a form? I want users to be able to hold down the control key while submitting a form and have the result open in a ...

Transform the JSON data to generate a fresh JSON output

I'm seeking help to develop a script that generates JSON data based on specific conditions. As of now, I believe my logic is correct. Any assistance would be greatly appreciated. CURRENT ISSUES: [resolved]I am unable to determine why the duration ...

The V-model is failing to bind properly as anticipated

One feature of my application involves a table that displays a list of products. Each product row in the table has an input field where users can enter the quantity they want to purchase. The total cost for each product is dynamically calculated by multipl ...

jQuery failing to append code after being removed

I need some assistance with an issue I've run into while using jQuery's .remove(). Here is a snippet of code that showcases the problem: $( '.video-button span.glyphicon-play' ).click(function() { $( '#video-player' ).ap ...