Dynamic import doesn't work with SVG imported as ReactComponents
  • 21-May-2023
Lightrun Team
Author Lightrun Team
Share
Dynamic import doesn't work with SVG imported as ReactComponents

Dynamic import doesn’t work with SVG imported as ReactComponents

Lightrun Team
Lightrun Team
21-May-2023

Explanation of the problem

 

This bug report outlines an issue related to importing an SVG file as a ReactComponent using dynamic import(). The expected behavior is that the SVG file should load successfully, but the actual behavior results in an error in the browser. The error message indicates that the element type is invalid, and it suggests possible reasons for this error, such as forgetting to export the component or mixing up default and named imports. The cause of the error is identified as the imported module not containing the ReactComponent property.

To provide a reproducible demo, the code snippet showcases a React component called “App” that attempts to import and render the SVG file. Inside the componentDidMount() lifecycle method, the SVG file is imported using dynamic import, and upon successful import, the ReactComponent property of the module is assigned to the “logoComponent” variable. However, due to the missing ReactComponent property in the imported module, the error occurs when attempting to render the component.

A workaround for this issue is suggested, which involves creating a separate file that directly imports the SVG file using the ReactComponent syntax. This file exports the component, and it can be used in the main component file without relying on dynamic import. By following this workaround, the SVG file can be successfully imported and used as a React component.

 

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: Dynamic import doesn’t work with SVG imported as ReactComponents

 

To solve the problem of importing an SVG file as a ReactComponent using dynamic import, you need to ensure that the imported module contains the necessary ReactComponent property. Here’s a step-by-step solution:

  1. Create a separate file, let’s call it “Logo.js”, to handle the import and export of the SVG file as a React component.
  2. Inside “Logo.js”, use the following syntax to import the SVG file and assign it to the ReactComponent variable:

 

import { ReactComponent } from './logo.svg';
export default ReactComponent;

 

  1. Save the file and make sure it is in the same directory as your main component file.
  2. In your main component file, modify the import statement to use the new “Logo” component from “Logo.js” instead of dynamic import:

 

import React from 'react';
import './App.css';
import Logo from './Logo';

class App extends React.Component {
  render() {
    return (
      <div>
        <Logo />
      </div>
    );
  }
}

export default App;

 

  1. Save the changes and run your application again. The SVG file should now load successfully and be rendered as a React component.

By creating a separate file that directly imports the SVG file using the ReactComponent syntax and exporting it, you avoid the issue of the missing ReactComponent property in the imported module. This solution ensures that the SVG file is correctly imported and rendered as a React component without encountering the “Element type is invalid” error.

 

Problems with create-react-app

 

Problem 1: “Error: ENOSPC: System limit for number of file watchers reached” Description: This error occurs when the system limit for the number of file watchers is reached. It typically happens in development environments with many files being watched, such as when running create-react-app with hot reloading enabled.

Solution: To resolve this issue, you need to increase the number of file watchers allowed by the system. One way to do this is by modifying the fs.inotify.max_user_watches value in the sysctl configuration.

First, check the current value:

 

sysctl fs.inotify.max_user_watches

 

If the value is lower than what you need (e.g., 8192), you can temporarily increase it:

 

sudo sysctl -w fs.inotify.max_user_watches=8192

 

To make the change permanent, update the sysctl.conf file:

 

echo fs.inotify.max_user_watches=8192 | sudo tee -a /etc/sysctl.conf
sudo sysctl -p

 

Problem 2: “Invalid host header” when running the application in development mode Description: This error occurs when the host specified in the development server configuration does not match the host header sent by the browser. It is a security measure to prevent cross-origin attacks.

Solution: To fix this issue, you can configure the development server to allow the specific host header. Edit the package.json file in your project and add a "proxy" field:

 

"proxy": "http://localhost:3001"

 

Replace "http://localhost:3001" with the appropriate URL or hostname of your API server.

Problem 3: “Module not found” error when importing files with absolute paths Description: create-react-app does not support importing files with absolute paths by default. Attempting to import a file using an absolute path will result in a “Module not found” error.

Solution: To enable importing files with absolute paths, you can configure the jsconfig.json or tsconfig.json file in your project. Create the file if it doesn’t exist and add the following configuration:

 

{
  "compilerOptions": {
    "baseUrl": "src"
  },
  "include": ["src"]
}

 

This configuration sets the baseUrl to the "src" directory, allowing you to import files using absolute paths relative to the src directory.

 

A brief introduction to create-react-app

 

create-react-app is a command-line tool that provides a streamlined and opinionated setup for creating React applications. It is designed to simplify the initial setup process by abstracting away complex configurations and build tool configurations, allowing developers to focus on writing code rather than configuring the development environment. When creating a new project with create-react-app, it sets up a preconfigured development server, a production-ready build configuration, and a sensible project structure.

Under the hood, create-react-app utilizes modern JavaScript features such as Babel for transpiling and Webpack for bundling. It includes several essential development dependencies, such as React, ReactDOM, and the necessary scripts to start, build, and test the application. Additionally, create-react-app supports features like hot reloading, which allows developers to see the changes in real-time as they edit the code.

Using create-react-app enables developers to quickly scaffold a React application with best practices and conventions in place. It abstracts away the complexities of configuration, allowing developers to focus on writing application logic and UI components. With its robust development server and build configurations, create-react-app provides an efficient and reliable foundation for building scalable and maintainable React applications.

 

Most popular use cases for create-react-app

  1. Rapid React Application Setup: create-react-app is an excellent tool for quickly setting up a new React application. By running a single command, developers can create a project with a ready-to-use development environment and build configurations. The following code block demonstrates how simple it is to create a new React application using create-react-app:
npx create-react-app my-app
  1. Streamlined Development Workflow: create-react-app offers a streamlined development workflow by providing features like hot reloading, which automatically updates the application in the browser as changes are made to the source code. This feature eliminates the need for manual page refreshes, making the development process faster and more efficient. Developers can simply focus on writing code, and the changes will be immediately reflected in the running application.
  2. Production-Ready Build Configuration: create-react-app generates an optimized production build configuration out of the box. It performs minification, code splitting, and other optimizations to ensure the resulting bundle is lightweight and performs well. The following code block demonstrates how to build a production-ready version of the application:
npm run build
The build command generates a production build in the build directory, ready to be deployed to a web server or static file hosting service. This allows developers to easily package their React application for production deployment and ensures optimal performance.
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.