Ionic Icons with NextJs

4 weeks ago | 1 minute read | ReactJs | NextJs

Ion icon in NextJs

So recently I was trying to get Ionicons to work with a NextJS application I was playing around with and I had trouble pulling it in. Here's my way around it.

First we can't use ion-icon tag within your code like:

// Wrong - won't work
const Page = () => {
  return <div><ion-icon name='search'/> </div>
};

export default Page;

You probably know this already, this is because ion-icon isn't a native tag. We need to let NextJs know they don't need to parse that tag.

Before we continue, you'll need to extends your _document.jsx or app_jsx (js, jsx, ts, tsx depends on you) to load the ion-icon scripts.

import { Html, Head, Main, NextScript } from 'next/document';

const Document = () => {
  return (
    <Html lang='en'>
      <Head />
      <body> 
        <Main />
        <NextScript />
        <script src='https://unpkg.com/ionicons@5.5.2/dist/ionicons/ionicons.esm.js' type='module'><script/>
        <script src='https://unpkg.com/ionicons@5.5.2/dist/ionicons/ionicons.js' noModule></script/>
      </body> 
    </Html>
  );
}

export default Document;

If you should import this within your app.jsx, use next/script component.

Now that we have ion icons pulled in, we can render an icon with dangerouslySetInnerHTML like:

const somePage = () => {
  return (
    <div>
      <i dangerouslySetInnerHTML={{
          __html: "<ion-icon name='search-outline' />",
      }}></i>
    </div>
  );
}

export default somePage

That's all it takes. But you'll agree with me that's a long syntax just to render an icon. You can factor this to a seperate component. Something like:

const Icon = ({ name, size = null }) =>  {
  return (
    <i dangerouslySetInnerHTML={{
      __html: `<ion-icon name='${name}' size='${size}'/>`
    }}></i>
  );
}
export default Icon;

Now, within your application we can do this.

import Icon from '../components/logo.jsx';

const SomePage = () => {
  return (
    <div>
      <Icon name='search-outline' size='large'/>
    </div>
  );
}

export default SomePage;

You can check ionic icon documentation for icon names.