Home > Mobile >  Reactjs and typescript assign randomly generated variable to div style width and height
Reactjs and typescript assign randomly generated variable to div style width and height

Time:12-26

i am trying to assign randomly generated variable as width and height to div, so far i have written the function for generating random size but i get error when i'm trying to assign it to style

my goal is to generate new div everytime button is clicked

this is so far what i have written, i get error on :

style={{width:divSize}}

which says:

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

CodePudding user response:

Declare the divSize Before the if

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