Module not found: Error: Can't resolve React
  • 27-Apr-2023
Lightrun Team
Author Lightrun Team
Share
Module not found: Error: Can't resolve React

Error: Can’t resolve ‘React’ in ‘/home/capaj/project/node_modules/react-visibility-sensor/dist’

Lightrun Team
Lightrun Team
27-Apr-2023

Explanation of the problem

An issue with importing react-visibility-sensor version 5.0.2 into my application, which uses webpack version 4. When tried to import the package using the following statement:

import VisibilitySensor from “react-visibility-sensor”

Received an error message, stating that the module “React” could not be found in the specified path. The error message specifically points to the file “visibility-sensor.js” located in the “react-visibility-sensor/dist” directory.

Similarly, when tried to import the “ReactDOM” module using the same statement, received another error message indicating that the specified module could not be found in the same path as the previous error.

Troubleshooting with the Lightrun Developer Observability Platform

 

Getting a sense of what’s actually happening inside a live application is a frustrating experience, one that relies mostly on querying and observing whatever logs were written during development.
Lightrun is a Developer Observability Platform, allowing developers to add telemetry to live applications in real-time, on-demand, and right from the IDE.

  • Instantly add logs to, set metrics in, and take snapshots of live applications
  • Insights delivered straight to your IDE or CLI
  • Works where you do: dev, QA, staging, CI/CD, and production

Start for free today

Problem solution for Module not found: Error: Can’t resolve ‘React’ in ‘/home/capaj/project/node_modules/react-visibility-sensor/dist’

The problem encountered when importing react-visibility-sensor in a webpack 4 environment stems from webpack’s module resolution algorithm. Specifically, webpack assumes that the application is running in a UMD (Universal Module Definition) loader, which causes it to try to load dependencies from global sources. This assumption is not always accurate, which leads to issues such as the “module not found” error.

One solution for this problem is to configure webpack to skip transpilation for react-visibility-sensor, instead of importing a specific file. This is a more sustainable solution that is not impacted by changes in the package’s file structure. The suggested method is to exclude the react-visibility-sensor package from transpilation using babel-loader. This can be achieved by adding the following code block to your webpack configuration:

{
  test: /\.js?$/,
  use: {
    loader: 'babel-loader',
    options: {
      cacheDirectory: true
    }
  },
  exclude: /node_modules\/react-visibility-sensor\/.*/
}

Another solution to the import issue is to import the “visibility-sensor” file specifically, rather than the entire react-visibility-sensor package. This can be achieved by changing the import statement to the following:

import VisibilitySensor from 'react-visibility-sensor/visibility-sensor'

This solution is a quick fix, but it may be affected by changes in the package’s file structure in future updates. Therefore, it is recommended to use the first solution for long-term sustainability.

It is important to note that this issue is specific to webpack 4 and does not occur in later versions of webpack. Therefore, upgrading to a newer version of webpack may also solve the problem.

Other popular problems with react-visibility-sensor

 

Problem: When the target element is positioned within a container with a fixed height and overflow set to auto

One common problem with react-visibility-sensor is related to its behavior in certain scenarios, specifically when the target element is positioned within a container with a fixed height and overflow set to auto. In this case, react-visibility-sensor does not trigger the visibility change event when the target element is scrolled into view. This behavior is caused by the fact that react-visibility-sensor uses the Intersection Observer API, which does not work as expected in certain scrollable containers.

Solution:

A potential solution for this issue is to add an additional layer of wrapper elements around the target element and set the overflow and position styles on these wrapper elements instead of the original container element. This approach allows the Intersection Observer API to work as expected and trigger the visibility change event. Additionally, some users have reported success with using alternative libraries or writing custom Intersection Observer logic to achieve the desired behavior.

Problem: Compatibility issues with older browsers

Another common problem with react-visibility-sensor is related to compatibility issues with older browsers, specifically Internet Explorer 11. This issue is caused by the fact that the Intersection Observer API is not supported in Internet Explorer 11, which means that react-visibility-sensor does not work in this browser.

Solution:

A potential solution for this issue is to use a polyfill library to add support for the Intersection Observer API in older browsers. One popular polyfill library is “intersection-observer”, which can be installed via npm and imported into the application. This library provides a shim for the Intersection Observer API, which allows react-visibility-sensor to work in older browsers such as Internet Explorer 11.

Problem: Compatibility with certain CSS frameworks or styling libraries

A third common problem with react-visibility-sensor is related to the library’s compatibility with certain CSS frameworks or styling libraries. Specifically, react-visibility-sensor may not work correctly when used within a component that is positioned using CSS grid or flexbox layout. This issue is caused by the fact that the Intersection Observer API relies on the layout of the page to determine visibility, and certain CSS layouts can interfere with this process.

Solution:

A third common problem with react-visibility-sensor is related to the library’s compatibility with certain CSS frameworks or styling libraries. Specifically, react-visibility-sensor may not work correctly when used within a component that is positioned using CSS grid or flexbox layout. This issue is caused by the fact that the Intersection Observer API relies on the layout of the page to determine visibility, and certain CSS layouts can interfere with this process.

A brief introduction of react-visibility-sensor

The core functionality of react-visibility-sensor is based on the Intersection Observer API, which is a browser API that allows you to detect when an element intersects with another element or the viewport. React-visibility-sensor abstracts away the complexity of using the Intersection Observer API and provides a simpler React-based API. The component takes a single child element and triggers a callback function when the element becomes visible or invisible. The callback function can be used to perform actions such as fetching more data, changing the state of the component, or triggering an animation.

Most popular use cases for react-visibility-sensor

  1. One of the most common use cases for react-visibility-sensor is lazy loading of images or components. This means that instead of loading all the images or components upfront, only the ones that are visible on the screen are loaded. This improves the performance of the application by reducing the initial load time and reducing the amount of data transferred. The following code block demonstrates how to use react-visibility-sensor for lazy loading of images:
    import VisibilitySensor from 'react-visibility-sensor';
    
    function LazyImage(props) {
      const [isVisible, setIsVisible] = useState(false);
    
      const onVisibilityChange = (isVisible) => {
        setIsVisible(isVisible);
      };
    
      return (
        <VisibilitySensor onChange={onVisibilityChange}>
          <img src={isVisible ? props.src : 'placeholder.png'} />
        </VisibilitySensor>
      );
    }

    In this example, the LazyImage component takes a src prop that contains the URL of the image to be loaded. The component wraps the img element in a VisibilitySensor component and passes an onVisibilityChange function as a prop. The onVisibilityChange function updates the state of the component when the image becomes visible, and the img element’s src attribute is updated accordingly.

    2. Another use case for react-visibility-sensor is implementing infinite scrolling. Infinite scrolling is a technique where new content is loaded as the user scrolls down the page, providing a seamless user experience without the need for pagination. The following code block demonstrates how to use react-visibility-sensor for infinite scrolling:

    import VisibilitySensor from 'react-visibility-sensor';
    
    function InfiniteScroll(props) {
      const [page, setPage] = useState(1);
      const [isLoading, setIsLoading] = useState(false);
      const [isEndReached, setIsEndReached] = useState(false);
    
      const loadMore = async () => {
        if (isLoading || isEndReached) {
          return;
        }
    
        setIsLoading(true);
    
        // Fetch data from API
        const newData = await fetch(`https://api.example.com/data?page=${page}`);
    
        setIsLoading(false);
    
        if (newData.length === 0) {
          setIsEndReached(true);
        } else {
          setPage(page + 1);
          props.onLoadMore(newData);
        }
      };
    
      const onVisibilityChange = (isVisible) => {
        if (isVisible) {
          loadMore();
        }
      };
    
      return (
        <>
          {props.children}
          {!isEndReached && <VisibilitySensor onChange={onVisibilityChange} />}
        </>
      );
    }
    

    In this example, the InfiniteScroll component takes a children prop that contains the initial content to be displayed and an onLoadMoreproploadMore function is called when the user reaches the end of the page, and new data is fetched from the API. The onVisibilityChange function is passed to the VisibilitySensor component and triggers loadMore when the user reaches the end of the page.

    3. Finally, react-visibility-sensor can be used to trigger animations when an element becomes visible on the screen. This is useful when you want to animate an element as it enters the viewport, providing a more engaging user experience. The following code block demonstrates how to use react-visibility-sensor to trigger an animation:

    import VisibilitySensor from 'react-visibility-sensor';
    import { useSpring, animated } from 'react-spring';
    

     

Share

It’s Really not that Complicated.

You can actually understand what’s going on inside your live applications.

Try Lightrun’s Playground

Lets Talk!

Looking for more information about Lightrun and debugging?
We’d love to hear from you!
Drop us a line and we’ll get back to you shortly.

By submitting this form, I agree to Lightrun’s Privacy Policy and Terms of Use.