Implementing SVG in NextJS 13 with custom app directory: A step-by-step guide

Recently, I decided to explore the app directory and unfortunately ran into some issues. One of the main problems I encountered was with image imports. While PNG images imported without any problem, SVG images seemed to break when importing in /app.

For instance, there was a specific URL that worked perfectly fine in /pages but failed in /app:

import Logo from 'public/company.svg';

When checking the imported image object (from within the component), it appeared like this in the console:

{
  src: '/_next/static/media/company.99a082b8.svg',
  height: 32,
  width: 162
}

Interestingly, the actual file was missing in the /media folder.

I am now wondering how I can effectively import SVG images into my NextJS 13+ project?

Update:

To resolve the issue, I have incorporated SVGR for importing SVGs as components, which has resolved functionality; however, the build issue still remains unresolved.

Answer №1

If you're facing issues with using SVG images as src, @svgr/webpack can help solve the problem. One workaround is to utilize Image from next/image like so - instead of using the <img/> tag which may not work properly.

import Image from "next/image";
import SVGIMG from "../public/vercel.svg";

export default function Page() {
    return (
       <Image src={SVGIMG} alt={""}/>
    )
}

This solution has been tested and works smoothly in both next dev and next build && next start environments!

Answer №2

If you're looking to convert an SVG into a React Component, the SVGR Playground is a useful tool for achieving this. By importing the converted component, you can easily incorporate it into your project like any other React Component. To customize the color of the SVG, simply modify the fill attribute in the SVG component to "currentColor" and remove any additional fill attributes. From there, you can apply styling using CSS or frameworks such as Tailwind. Adjusting the size of the SVG can be done by passing width and height as props, although sometimes scaling may not work as expected.

Answer №3

//To easily incorporate an svg icon, create a component and insert the svg code inside the return statement. Make sure to remove the xml, style, and fill attributes from the svg code.

let TwitterIcon = () => {
  return (
    <svg version="1.1" id="Layer_1" x="0px" y="0px" viewBox="0 0 90 90">
      <path
        id="Path_947"
        d="M5.06,44.96c0-7.72-0.1-15.44,0.04-23.15c0.11-5.04,2.51-9.76,6.53-12.82
    C14.68,6.41,18.56,5,22.56,5.02c15.09,0,30.18-0.08,45.27,0.06c6.21,0.02,11.91,3.45,14.84,8.94c1.6,2.73,2.41,5.85,2.33,9.01
    c0,14.67-0.07,29.3,0,43.96c0.03,8.56-5.97,15.95-14.35,17.69c-1.29,0.24-2.6,0.34-3.91,0.31c-14.49,0-28.99-0.05-43.49,0.04
    c-8.63,0.1-16.13-5.89-17.92-14.33C5.08,69.35,4.97,67.98,5,66.61c0-7.22,0-14.43,0-21.65H5.06 M44.94,70.86
    c14.29,0.03,25.91-11.52,25.94-25.82c0.03-14.29-11.53-25.91-25.82-25.94S19.15,30.63,19.12,44.92c0,0.07,0,0.14,0,0.21
    C19.22,59.34,30.74,70.81,44.94,70.86 M76.9,18.33c0.07-2.95-2.27-5.39-5.21-5.45c-0.07,0-0.14,0-0.21,0
    c-3-0.03-5.46,2.38-5.49,5.38c0,0.05,0,0.09,0,0.14c0.08,2.97,2.48,5.36,5.46,5.41C74.46,23.79,76.9,21.34,76.9,18.33 M44.97,59.66
    c-8.1-0.03-14.65-6.62-14.62-14.72s6.62-14.65,14.72-14.62s14.64,6.61,14.62,14.7C59.64,53.11,53.07,59.64,44.97,59.66"
      />
    </svg>
  );
};

export default TwitterIcon;

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

ways to halt a noise once an animation is complete

I don't have much experience with coding in general, but somehow I've made it this far. Now I'm stuck on the final piece of the puzzle. This is related to a Twitch alert that I'm setting up through 'Stream Elements'. The iss ...

Unexpectedly, optimization causing issues on Angular site without explanation

Currently, I am utilizing Angular to construct a front-end website that searches for and showcases information obtained through API requests. Whenever I compile the project into a file bundle for static deployment using ng build, I notice that the resultin ...

Error: The 'encoding' property cannot be set on null objects in THREE.js

I have been trying to load a basic grass block from Minecraft, but I keep encountering an error message that says TypeError: Cannot set properties of null (setting 'encoding'). This error originates from line 2893 in GLTFLoader, specifically the ...

What is the reason behind the `h-full`/`height:100%` not completely filling the void within a div element?

The issue lies in the structure of my content, which includes a title, a subtitle, and a footer. My desire is for the subtitle's div to fill the gap between the title and the footer. I attempted using h-full on the div element, but it had no noticeab ...

The getInitialProps method does not have access to the Passport user object in the request when the server is running on a different port

I currently have my express server running on a separate port from my client-side nextjs project. Typically, when the server is on the same port as the client, you can use getRequestHandler with next to pass the user object that can be accessed in the cli ...

Implement a termination condition for mapping in React

Here is a code snippet to consider: <TableHead> {documents.map((docs, i) => ( <TableRow key={i}> <TableCell> {{docs.name} </TableCell> </TableRow> ))} </TableHead> I am looking for a wa ...

Implement the callback-console.log feature from the epic-games-api into an Express.js application

Looking to integrate Epic Games output into an Express.js GET request but don't have any JavaScript experience, so go easy on me! XD const EpicGamesAPI = require('epicgames-status'); const express = require('express') const app = ...

Using ASP.NET MVC to transmit JSON information to a Controller method

Even after multiple attempts, I am unable to send JSON data to my ASP.NET MVC3 controller action method successfully. Below is the ajax call I am using (it utilizes the JSON.stringify method from json2.js): $.ajax({ url: '/Home/GetData', ...

When using iOS, the video compressing process stops automatically if the screen is no longer active while the file input

I am working on a web application that includes a file upload feature for large videos, typically 30 minutes or longer in duration. When a user on an iOS device selects a video to upload, the operating system will automatically compress it before triggerin ...

When the onload event is triggered, the jscript function called var data is loaded, without any interruption in

I encountered an issue while trying to preview an image from a BBCode decoder. The code works fine, but I need the image to be inside an <a> href link, so that people can click on it and get the image source. Additionally, I want to display a message ...

What should I do when using _.extend() in express - override or add in fields?

When an object is extended by another object with values set for some of the extended fields, will it be rewritten or will the new values be added? For example: const PATCH_REQUEST_SCHEMA = { 'type': 'object', 'title' ...

Properties of a child class are unable to be set from the constructor of the parent class

In my current Next.js project, I am utilizing the following code snippet and experiencing an issue where only n1 is logged: class A { // A: Model constructor(source){ Object.keys(source) .forEach(key => { if(!this[key]){ ...

What is the best way to save the properties of elements in an array of objects within another array?

I have obtained attributes from objects within an array that I need to store in another array. Here is the data I am working with: https://i.sstatic.net/b0JtY.jpg My goal is to extract the `displays` name attribute and save it in the `opt[]` array, which ...

Creating a specific type of table using Ruby on Rails

Is it feasible to create a table with two columns, where the left column incorporates multiple rows with a scroll bar, and the right column contains a large box housing buttons that alter based on the selection of blocks in the left column? ...

Challenges faced when retrieving data from a web API using JavaScript with REACT

Having trouble retrieving data from a Web API in React. The API URL is and I've stored it in a state called pokeData. When I do a console.log(pokeData), everything works fine. Likewise, there are no issues with console.log(pokeData.types). However, ...

Alter the class names on a div element every 3 seconds using React

Looking to animate the movement of CSS classes sequentially? Imagine starting with an image and after 3 seconds, shifting all classes downward so the last one appears on top, creating a dynamic carousel effect. Any assistance would be greatly appreciated! ...

Divide a SINGLE BACKGROUND IMAGE in HTML into two separate links of equal size, one at the top and

As a beginner in HTML, I am trying to find a way to divide a background image into two equal sections without using image mapping. I attempted to split the links by setting the style to 0% and 50% to designate the top and bottom halves, but unfortunately, ...

The controller function is not triggered if the user does not have administrator privileges

I have a code snippet in which my controller function is not being triggered for users who do not have the role of "Admin". Can someone help me identify where I went wrong? Just to clarify, the controller function works fine for users with the role of "Adm ...

Limiting the number of characters in a textarea using React with TypeScript

Having encountered two issues, I've developed a textarea component that not only allows users to input text but also keeps track of the number of characters they have typed. First Issue: I'm attempting to check if the length of the current input ...

Using the srcSet attribute with the Nextjs Image component

Is there a way to load different images for mobile viewport since passing srcSet in Next.js does not seem to work? Currently, I am using CSS display property to achieve this functionality but I would prefer something similar to the code snippet below: < ...