Utilizing Reactjs and typescript to dynamically set width and height properties of a div element using randomly generated variables

I am attempting to set a randomly generated variable as the width and height of a div. I have successfully written a function that generates a random size, but encounter an error when trying to assign it to the style attribute.

My objective is to create a new div every time a button is clicked.

Here is my current progress:

style={{width:divSize}}

The error message states:

Variable 'divSize' is used before being assigned.ts(2454)
function createRandomRectangle(){
  if (boxxy!=null) {
    var divSize = Math.round(((Math.random()*200) + 50));
    const width = boxxy.offsetWidth , height =boxxy.offsetHeight;
    var posX = Math.round((Math.random() * ( width- divSize)));
    var posY = Math.round((Math.random() * (  height- divSize)));
  }
  return(
    <div className='Rectangle' style={{width:divSize}}></div>
  )
  
}

Answer №1

Rearrange the Declaration of divSize

function createRandomRectangle() {
let divSize;
if (boxxy != null) {
divSize = Math.round(((Math.random()*200) + 50));
const width = boxxy.offsetWidth , height = boxxy.offsetHeight;
var posX = Math.round((Math.random() * (width - divSize)));
var posY = Math.round((Math.random() * (height - divSize)));

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

Controlling the visibility of one class from another class in CSS: To disable or enable visibility

Struggling to make a class visible when hovering over its parent class in CSS? Want to activate the submenu class on hover effect over the menu class? Here is the HTML code: <li class="menu"><a href="#">Link</a></li> <ul ...

Using jQuery for slide shows in Ruby on Rails framework

I'm attempting to create a slideshow using jQuery and have the images stored in an array. However, I'm struggling with the implementation of the slideshow functionality. I've checked out 'http://jquery.malsup.com/cycle/' for guidan ...

Creating Global Variables in Node/Express Following a Post/Get Request

How can I dynamically pass the payment ID received after a POST request to a subsequent GET request in Node/Express for a payment system? Below is an example code snippet from my project: let paymentId; app.post("/api/payments", (req, res) => ...

What is the best way to integrate Angular types (excluding JS) into tsconfig to avoid the need for importing them constantly?

Lately, I've been dedicated to finding a solution for incorporating Angular types directly into my .d.ts files without the need to import them elsewhere. Initially, I attempted to install @types/angular, only to realize it was meant for AngularJS, whi ...

What is the ideal timing to incorporate an error handler in an Observable?

I find myself uncertain about the best practices for error handling in general. For instance, if I'm already handling errors in my service using catchError, is it necessary to also include an error handler in my subscription? Here's an example o ...

Dynamic properties in JQuery

Here is the HTML DOM element I have... <input type="text" style="width: 200px;" id="input1"/> I want to make sure it stores date values. How can I specify that in the DOM element? Please provide your suggestions. Thanks! ...

Can you explain the function of MathUtils.euclideanModulo and how it sets itself apart from the traditional modulo operation?

I'm a little puzzled by the euclideanModulo function in threejs's mathutils. I understand the concept of the modulo operator, but the euclideanModulo function seems to work differently. ( ( n % m ) + m ) % m I tried researching the meaning of "E ...

Using Javascript to redirect to a link using JSON

Is there a way to display the CustomerPartial without reloading the page or triggering a postback when a button is clicked? Currently, when I click the button, data is posted to Home/Customer but the browser link always remains as: localhost:49461 How ca ...

What is the process for accessing a table in indexedDB using Dexie.js immediately after it has been opened?

I am faced with the challenge of needing to verify if a specific table already exists in IndexedDB right after it has been opened. However, I am unsure how to access the DexieDB object inside the 'then' statement. this.db = new Dexie("DBNAME"); ...

Guide on navigating from a React page to an Express page

Hi, I'm trying to figure out how to redirect a React page to an Express page in order to send an email if a user forgets their password. I attempted to use Router, but it redirected me to 'localhost:3000/forgot_password' instead of 'loc ...

Store the response data in a global variable or forward it to another function in Node.js using Express JS

I'm currently working on a function that makes a post request to an API (app.post), sending a token and a URL for redirection to webpay. The challenge I'm facing is saving that token in a global variable so that it can be accessed by another func ...

Creating a Runescape Tracker: What essentials should I include?

Hello everyone, I am a beginner in the world of programming and I am excited to learn. I have heard that the best way to learn is by working on a project. I have always been interested in creating a Skill Tracker for my clan. Can you offer any advice on wh ...

Are Next.js API directory and files secure for saving sensitive information like API keys, secret words, and more?

I am in the process of creating a straightforward Next.js route specifically designed for managing payments. Within this route's handler, I am communicating with a third-party service using fetch to facilitate payment processing. To ensure security, o ...

The model seems to have loaded successfully but is not displayed

Struggling to make a model from an .obj file load and be visible in Three.js. New to this, so seeking help! Here is my code so far: const renderer = new THREE.WebGLRenderer({ antialias: true }); renderer.setSize(window.innerWidth, window.innerHeight); ...

Steps for removing the footer from WordPress with the "powered by WordPress" message:

I am curious about how to delete the footer that says "powered by wordpress". I created this page and at the bottom of it, there is a mention of "powered by wordpress". Website ...

Steps to retrieve values from a grid and execute a sum operation using PROTRACTOR

Embarking on my Protractor and Javascript journey, I am faced with the challenge of writing a test script to retrieve values of various accounts under the header "Revenue" (as shown in the image below). My task involves extracting all number values listed ...

How can I create a notification popup triggered by a button click with Ajax and Javascript?

I'm in the process of developing a website that involves notifications, but I am unsure how to display them when a button is pressed. For example, clicking "Show Weather" should trigger a notification to appear in the bottom corner of the page. https ...

Can Angular be used to dynamically filter a JSON object to display only the fields that match a specified filter text?

Sorry if this question has already been asked; I couldn't find the solution. Here is my issue: In my Angular app, I am retrieving a complex JSON object from a web service. I then present this JSON object to the user in tree format using ngx json vie ...

Refresh the table dynamically in Django without the need to reload the entire page

Seeking assistance to update a small table with new data every 10 seconds on a Django website. The data is parsed into JSON and refreshed in the database, then displayed on the front-end. Looking for help with writing AJAX code to continuously refresh the ...

Vue is having trouble loading dynamic src files, and the require function isn't functioning properly

I'm facing an issue with displaying a dynamic image. When I use the following code: <img :src="src" alt="img"> It doesn't seem to work. However, it works perfectly fine when I use: <img src="../assets/img/banana ...