A guide on detecting overflow in a React functional component

I am in search of a way to determine if a div contains overflowing text and display a "show more" link if it does. While researching, I came across an insightful Stack Overflow answer on checking for overflow in a div. The answer suggests implementing a function that can access the styles of the element and perform checks to ascertain if it is overflowing. How can one access the styles of an element effectively? I attempted two different methods.

1. Utilizing ref

import React from "react";
import "./styles.css";

export default function App(props) {
  const [showMore, setShowMore] = React.useState(false);
  const onClick = () => {
    setShowMore(!showMore);
  };

  const checkOverflow = () => {
    const el = ref.current;
    const curOverflow = el.style.overflow;

    if (!curOverflow || curOverflow === "visible")
        el.style.overflow = "hidden";

    const isOverflowing = el.clientWidth < el.scrollWidth 
        || el.clientHeight < el.scrollHeight;

    el.style.overflow = curOverflow;

    return isOverflowing;
  };

  const ref = React.createRef();

  return (
    <>
      <div ref={ref} className={showMore ? "container-nowrap" : "container"}>
        {props.text}
      </div>
      {checkOverflow() && <span className="link" onClick={onClick}>
        {showMore ? "show less" : "show more"}
      </span>}
    </>
  )
}

2. Using forward ref

Child component

export const App = React.forwardRef((props, ref) => {
  const [showMore, setShowMore] = React.useState(false);
  const onClick = () => {
    setShowMore(!showMore);
  };

  const checkOverflow = () => {
    const el = ref.current;
    const curOverflow = el.style.overflow;

    if (!curOverflow || curOverflow === "visible") el.style.overflow = "hidden";

    const isOverflowing =
      el.clientWidth < el.scrollWidth || el.clientHeight < el.scrollHeight;

    el.style.overflow = curOverflow;

    return isOverflowing;
  };

  return (
    <>
      <div ref={ref} className={showMore ? "container-nowrap" : "container"}>
        {props.text}
      </div>
      {checkOverflow() && (
        <span className="link" onClick={onClick}>
          {showMore ? "show less" : "show more"}
        </span>
      )}
    </>
  );
});

Parent component

import React from "react";
import ReactDOM from "react-dom";

import { App } from "./App";

const rootElement = document.getElementById("root");
const ref = React.createRef();
ReactDOM.render(
  <React.StrictMode>
    <App
      ref={ref}
      text="Start editing to see some magic happen! Click show more to expand and show less to collapse the text"
    />
  </React.StrictMode>,
  rootElement
);

However, both approaches resulted in the error message -

Cannot read property 'style' of null
. What could be causing this issue? How can I accomplish my objective successfully?

Answer №1

Upon following Jamie Dixon's advice in the discussion, I implemented the useLayoutEffect hook to update the state of showLink to true. Below is the modified code snippet:

Component

import React from "react";
import "./styles.css";

export default function App(props) {
  const ref = React.createRef();
  const [showMore, setShowMore] = React.useState(false);
  const [showLink, setShowLink] = React.useState(false);

  React.useLayoutEffect(() => {
    if (ref.current.clientWidth < ref.current.scrollWidth) {
      setShowLink(true);
    }
  }, [ref]);

  const onClickMore = () => {
    setShowMore(!showMore);
  };

  return (
    <div>
      <div ref={ref} className={showMore ? "" : "container"}>
        {props.text}
      </div>
      {showLink && (
        <span className="link more" onClick={onClickMore}>
          {showMore ? "show less" : "show more"}
        </span>
      )}
    </div>
  );
}

CSS

.container {
  overflow-x: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  width: 200px;
}

.link {
  text-decoration: underline;
  cursor: pointer;
  color: #0d6aa8;
}

Answer №2

By implementing a custom hook, we can easily determine if there is overflow in our content.

import * as React from 'react';

const useIsOverflow = (ref, isVerticalOverflow, callback) => {
  const [isOverflow, setIsOverflow] = React.useState(undefined);

  React.useLayoutEffect(() => {
    const { current } = ref;
    const { clientWidth, scrollWidth, clientHeight, scrollHeight } = current;

    const trigger = () => {
      const hasOverflow = isVerticalOverflow ? scrollHeight > clientHeight : scrollWidth > clientWidth;

      setIsOverflow(hasOverflow);

      if (callback) callback(hasOverflow);
    };

    if (current) {
      trigger();
    }
  }, [callback, ref, isVerticalOverflow]);

  return isOverflow;
};

export default useIsOverflow;

You can simply incorporate this functionality into your component:

import * as React from 'react';

import { useIsOverflow } from './useIsOverflow';

const App = () => {
  const ref = React.useRef();
  const isOverflow = useIsOverflow(ref);

  console.log(isOverflow);
  // true

  return (
    <div style={{ overflow: 'auto', height: '100px' }} ref={ref}>
      <div style={{ height: '200px' }}>Hello React</div>
    </div>
  );
};

Credit goes to Robin Wieruch for his insightful articles

Answer №3

Implementing Solution with TypeScript and React Hooks

Begin by crafting your personalized hook:

import React from 'react'

interface OverflowY {
  ref: React.RefObject<HTMLDivElement>
  isOverflowY: boolean
}

export const useOverflowY = (
  callback?: (hasOverflow: boolean) => void
): OverflowY => {
  const [isOverflowY, setIsOverflowY] = React.useState(false)
  const ref = React.useRef<HTMLDivElement>(null)

  React.useLayoutEffect(() => {
    const { current } = ref

    if (current && hasOverflowY !== isOverflowY) {
      const hasOverflowY = current.scrollHeight > window.innerHeight
      // The right-hand side of the assignment could also be current.scrollHeight > current.clientWidth
      setIsOverflowY(hasOverflowY)
      callback?.(hasOverflowY)
    }
  }, [callback, ref])

  return { ref, isOverflowY }
}

Utilize your custom hook in your code:

const { ref, isOverflowY } = useOverflowY()
//...
<Box ref={ref}>
...your code here

Include necessary imports and adjust the code to meet your specific requirements.

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

What is the process to enable a tab in AngularJS using Foundation's tab feature?

Currently, I am utilizing AngularJS in conjunction with Foundations. Visit the official website for more information Within my page, there are two tabs that are functioning correctly as shown below: <tabset> <tab heading="tab1"> </tab ...

React setState issue experienced only on initial click due to API lag

My goal is to develop a web app using the Poke API to display multiple Pokemon. I have added buttons to allow users to "change the page" and switch the API URL to view the next or previous set of Pokemon. However, I'm facing an issue where the buttons ...

Single-select components in React Native

I am currently working on implementing a simple single selectable item feature, illustrated in the image provided below. https://i.stack.imgur.com/U2rJd.png At this moment, I have set up an array containing my data items and utilized the .map function to ...

Techniques for adjusting the dimensions of a select dropdown using CSS

Is there a way to control the height of a select dropdown list without changing the view using the size property? ...

Express.JS failing to save data to file when using NeDB

Currently, I am developing a bulk import feature for my personal password manager and I have encountered a problem. The issue arises when trying to import an array of passwords using the forEach() method to iterate through each one. After calling the inse ...

Decrease in font size observed after implementing Bootstrap 5

The issue arises when I include the Boostrap CDN link, resulting in a change in font size. I discovered that Bootstrap has a default font size, which is why attempts to adjust it using an external style sheet with !important do not succeed. Interestingly, ...

"Utilize AngularJS JavaScript to nest HTML elements within each other for dynamic web

I have developed a unique custom directive called hero. My goal is to set up a nested view for multiple instances of hero. Check out this demo to see it in action. The desired layout looks something like this: <hero a="1"> <hero a="2"> ...

Having trouble with the Slide Toggle menu closing unexpectedly?

$('span.nav-btn').click(function () { $('ul#menu').slideToggle(); }) $(window).resize(function () { if ( $(window).width() > 900) { $('ul#menu').removeAttr('style') } }); $('spa ...

What is the best way to duplicate several HTML input fields using jQuery?

My div is quite intricate with input fields structured like this <input type="text" name="firstname"> <input type="text" name="lastname"> <input type="text" name="email"> <input type="text" name="address"> <div id="section_toC ...

Guide to efficiently cache a React application using service workers

I'm currently facing an issue with trying to cache my entire app. I've attempted the following code snippet but it doesn't seem to be working as expected: self.addEventListener('install',(e)=>{ console.log( ...

Pressing element against another element

I have a somewhat unconventional request - I want to trigger a click event with an HTML element while hovering over another element. Let's imagine we have a .cursor element hovering over an anchor text. In this scenario, clicking on the .cursor shoul ...

Creating a notification feature for an HTML application

I am in the process of creating an HTML app through intel XDK. While I understand that using HTML to build apps is not as common, it is the language I am most familiar with, along with CSS. One feature I would like to include in my app is a weekly notific ...

The PHP equivalent of converting data to a JSON string, similar to the

When working with PHP's json_encode($array), I've noticed that diacritics can sometimes get messed up. However, if I update my database column to type text and pass javascript-created JSON over HTTP, everything appears fine. The issue arises when ...

What's the Hold-Up with IntersectionObserver in Brackets?

As a novice in the world of web development, I have been utilizing Brackets as my main tool. Recently, I've encountered a few hurdles specifically related to javascript. One issue I'm facing is trying to implement lazy loading on a div containing ...

Obtaining data with jQuery.Ajax technology

I am attempting to retrieve real-time data from a different URL and display it in a text field every second without refreshing the entire page. The content of the URL is constantly changing, so I want the field to update accordingly. However, despite my ef ...

Outputting PHP code as plain text with jQuery

My aim is to set up a preview HTML section where I am encountering a difficulty. I am struggling to display PHP code when retrieving and printing it from a textarea in the HTML. Here are my current codes, This is the HTML area where the textarea code will ...

Vanishing ShareThis Link After Postback in JavaScript

On my webpage at , I have included a ShareThis link in the footer that is generated via Javascript. However, whenever there is an AJAX postback after entering an email on the site, the link disappears. Is there a way to prevent this from happening and ensu ...

jsx eliminate parent based on dimensions

Imagine I have a DOM structured like this <div className="parent"> <div>child 1</div> <div>child 2</div> </div> If the view is on mobile, I would like the DOM to transform into <div>child 1</ ...

Alert: A notification appears when executing Karma on grunt stating that 'The API interface has been updated'

While executing karma from a grunt task, I encountered the following warning: Running "karma:unit" (karma) task Warning: The api interface has changed. Please use server = new Server(config, [done]) server.start() instead. Use --force to continue. A ...

Group the JSON data in JavaScript by applying a filter

I have a specific json object structure with keys cgi, tag and name, where the cgi key may be repeated in multiple objects. If any cgi has the tag 'revert', then that particular cgi should not be returned. [ { "cgi": "abc-123 ...