Marcus
Marcus

Reputation: 57

How to fix Cannot read property 'clientWidth' of null?

I am getting an error "Cannot read property 'clientWidth' of null" when I am resizing the window. I think, this is because, I am getting ref null. Any idea how can I fix it?

import React, { useRef, useState, useEffect } from "react";

const data = [
  "Some short text",
  "Some text that is a little bit longer",
  "Some text that will need to wrap but still fits on two lines",
  "A massive range of hammer drill machines and rotary hammers for SDS-plus accessory tools."
];
const TooltipDiv = props => {
  const divRef = useRef(null);
  const [allowTooltip, setAllowTooltip] = useState(false);
  useEffect(() => {
    if (!tooltip && divRef.current.scrollWidth > divRef.current.clientWidth) {
      setTooltip(true);
    } else if (window.addEventListener) {
      window.addEventListener('resize', () => {
        if (!tooltip && divRef.current.scrollWidth > divRef.current.clientWidth) {
            setTooltip(true);
        }
      })
    }
  }, [tooltip, divRef]);
  if (allowTooltip) {
    return (
      <Tooltip title={props.text}>
        <div ref={divRef} className={props.className}>
          {props.text}
        </div>
      </Tooltip>
    );
  }
  return (
    <div ref={divRef} className={props.className}>
      {props.text}
    </div>
  );
};
function App(props) {
  return (
    <>
      {data.map(text => {
        return (
          <>
            <TooltipDiv text={text} className={props.classes.listItem} />
          </>
        );
      })}
    </>
  );
}

I am getting an error "Cannot read property 'clientWidth' of null" when I am resizing the window. I think, this is because, I am getting ref null. Any idea how can I fix it?

Upvotes: 1

Views: 5731

Answers (1)

Lhew
Lhew

Reputation: 634

the window.addEventListener is trying to read a value that doesn't exist yet. At this moment, divRef is null.

I think you should try to test the existence of div.current and then, perform your if statement:

if(tooltip && divRef.current && divRef.current.scrollWidth && divRef.current.clientWidth){
  //your statement
}

also, try to perform the operation without [divRef, tooltip] because you want it to execute only once ([] ), I suppose

Upvotes: 2

Related Questions