Marcos Molina
Marcos Molina

Reputation: 39

Object is possibly 'undefined' in reference to paragraph HTML element

I have this functional component, I am trying to get the reference for check if the text holds more than 3 lines. Here is the part of the component.

export const Content = ({ content }: contentProps) => {
  const myRef: any = useRef(null);
        ......
  const threeLines = (): boolean => {
  // @ts-ignore
  const offset = myRef.current.offsetHeight;
  // @ts-ignore
  const lineHeight = parseInt(getComputedStyle(myRef.current).lineHeight);
 const lines = Math.floor(offset / lineHeight);
 console.log(lines);
 return lines < 3;
};
.........
      return (
        <div className="content">
          <p ref={myRef} className={show ? "text" : ""}>
            {content}
          </p>
          <br></br>
          {!isThreeLines ? (
            <button onClick={showToggle}> See {show ? "more" : "less"} </button>
          ) : null}
        </div>
      );

I don't want to set myRef: any. What's the problem? Why I am receiving Object is possibly 'undefined'?

edit: it occurs when I remove // @ts-ignore

Upvotes: 0

Views: 398

Answers (1)

Tom Finney
Tom Finney

Reputation: 2918

You want to type your ref properly like: const myRef = useRef<HTMLParagraphElement>(null)

And then secondly, because you can call your function anywhere, it can't guarantee that your ref.current will have a value so you will have to do a presence check or something like;

const threeLines = (): boolean => {
  let lines = 0;

  if (myRef.current) {
    const offset = myRef.current.offsetHeight;
    const lineHeight = parseInt(getComputedStyle(myRef.current).lineHeight);
    lines = Math.floor(offset / lineHeight);
  }

  return lines < 3;
};

I know that in the flow of your code and from your point of view, the ref will be set but you can also see why you get a type error for it.

Upvotes: 1

Related Questions