DEV Community

Cover image for Local Image not displaying in public folder EASY FIX - NextJS
goldenekpendu
goldenekpendu

Posted on

Local Image not displaying in public folder EASY FIX - NextJS

At the time of writing this article, I'm working on a NextJS project and I faced a particular issue that I would love to share with you.

Since this is my first time using NextJS, I had to read a lot of the documentation to make sure my folder structure was accurate and so I didn't mess anything up.

All my static assets were in the public folder and while also using Tailwind, I ran into an error. My images weren't showing up when I added the image source on the in-built Image component.

After minutes of making sure my paths were correct, and restarting my dev server (many times), I finally saw the issue!

Here is how my code looked before I saw what the issue was:

import Image from 'next/image'
const SampleImage = () => {
    return (
    <Image src={'/public/office.jpg'}/>
)
};

export default SampleImage;
Enter fullscreen mode Exit fullscreen mode

I realized that since my image was in the public folder, I didn't need my image path to have the /public prefix.

So here is the new line of code that displayed my images as I wanted:

import Image from 'next/image'
const SampleImage = () => {
    return (
    <Image src={'/office.jpg'}/>
)
};

export default SampleImage;
Enter fullscreen mode Exit fullscreen mode

If you're using Tailwind, you can use the following in your tailwind.config.js file:

/** @type {import('tailwindcss').Config} */
module.exports = {
  content: [
    './app/**/*.{js,ts,jsx,tsx,mdx}',
    './pages/**/*.{js,ts,jsx,tsx,mdx}',
    './components/**/*.{js,ts,jsx,tsx,mdx}',
  ],
  theme: {
    extend: {
      backgroundImage: {
        'office': "url('/office.jpg')",
      },

    },
  },
  plugins: [],
}
Enter fullscreen mode Exit fullscreen mode

It worked!

Based on your images, NextJS might throw an error requiring you to add the width and height properties to your image.

I look forward to learning way more about NextJS. Join me on this journey by following me. I'll update you regularly on new things I learn.

Thanks for reading and please share with someone who would like this ;)

Top comments (1)

Collapse
 
aik202 profile image
Assurance Chioma Ikogwe

I had this same error, I've been battling!! I've tried everything!!! Until I stumbled upon your post, and this was it!!!! Wow, thank you so so much, I just created an account on here, just to say thank you lol... Thank you so much!!!!