0

Javascript newbie here^^

In my React front, I have the following chrome error message :

Unhandled Rejection (TypeError): Cannot read property 'style' of null

▶ 2 stack frames were collapsed.

new LiquidFillGauge

SOMEPATH/liquidFillGauge.tsx:46

  43 | var gauge = d3.select('#' + elementId);
  44 | var radius = 0, locationX = 0, locationY = 0;
  45 | if (gauge != null && gauge != undefined) {
> 46 |     radius = Math.min(parseInt(gauge.style('width')), parseInt(gauge.style('height'))) / 2;
  47 | ^   locationX = parseInt(gauge.style('width')) / 2 - radius;
  48 |     locationY = parseInt(gauge.style('height')) / 2 - radius;
  49 | }

gauge being exceedingly checked in line 45, it still appears null in line 46.

Why is that happening ? How could I avoid the error ?

Thank you

2 Answers 2

1

Just do

if(gauge){
   radius = Math.min(parseInt(gauge.style('width')), parseInt(gauge.style('height'))) / 2; 
   locationX = parseInt(gauge.style('width')) / 2 - radius;
   locationY = parseInt(gauge.style('height')) / 2 - radius;
}

In javascript or typescript a null or undefined returns false.

Sign up to request clarification or add additional context in comments.

Comments

1

Because == stands just for equal type. You ought to use === which stands for equal type and equal value.

See this example:

let a = null;
let isNull = a != null;

isNull = false

To check null, undefined, false, you could do:

isEmpty = !gauge;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.