How to handle image files in a project with Storybook and Next.js?

Seito Horiguchi
1 min readMay 12, 2021

I‘ve been in a struggle to handle images in my project. The storybook page with Next.js couldn’t load the image files.

The specs of my project are as follows…

  • Storybook (6.2.7)
  • Next.js (10.1.3)
  • React (17.0.2)
  • TypeScript (4.2.4)

You can just resolve it with the following 3 steps.

1. package.json

You can just add this line to “./package.json”

"storybook": "start-storybook -s ./public -p 6006",

2. Preview.js

You can just add these codes to “./.storybook/preview.js”

import * as nextImage from 'next/image';

Object.defineProperty(nextImage, 'default', {
configurable: true, value: props => <img {...props} />
});
export const parameters = { actions: { argTypesRegex: '^on[A-Z].*' } };

3. Component file

You can put your specific image file on the directory “./public” and call it in your component by <Image/> from ‘next/image’ like this.

// Component.jsimport Image from 'next/image'const Component = () => {  return(
<Image
src='/image.jpg'
alt='background'
width={500}
height={500}
/>
)
}
export default Component

Since Next.js project understands your image file in “./public”, you can just write the path like “/image.jpg”.

BTW, I referred to this article and would like to appreciate the author, thank you!

https://xenox.dev/next-image-with-storybookjs

--

--