DEV Community

Nick Trierweiler
Nick Trierweiler

Posted on

Simple Free Flexible Styled SVG Icons in React

Simple Pattern to Use SVG Icons in a React App

When building a React app, it's common to need a variety of icons. You might use them for buttons, navigation, or simply for decoration. One of the best resources for free, high-quality icons is Tabler Icons.

In this blog post, I'll show you the simplest way to use svg icons in a React application, especially if you're already comfortable with creating React components.

Creating an Icon Component

Firstly, navigate to the Tabler Icons website and find an icon that you like, and copy the SVG code.

Note: If you are using your own .svg files, you can copy the html out of the file and place it directly in the component. Loading svg files in react can be overly complex, so I usually opt for this.

Create a new React component within the icons folder and paste the SVG code inside of a new component.

For example, let's create a search icon component:

// SearchIcon.tsx
const SearchIcon = ({ className = "" }: { className?: string }) => {
  return (
    <svg xmlns="http://www.w3.org/2000/svg" className={`${className} icon icon-tabler icon-tabler-search`} width="24" height="24" viewBox="0 0 24 24" strokeWidth="2" stroke="currentColor" fill="none" strokeLinecap="round" strokeLinejoin="round">
      <path stroke="none" d="M0 0h24v24H0z" fill="none"></path>
      <path d="M10 10m-7 0a7 7 0 1 0 14 0a7 7 0 1 0 -14 0"></path>
      <path d="M21 21l-6 -6"></path>
    </svg>
  );
};
export default SearchIcon;
Enter fullscreen mode Exit fullscreen mode

Customizing the Icon

Notice the optional className prop. This allows us to pass any Tailwind CSS classes (or any other classes) to style our icon, making it versatile. We can adjust the text color, background color, dimensions, and margins.

Basic Usage

import SearchIcon from './icons/SearchIcon';

const App = () => {
  return (
    <div>
      <SearchIcon />
    </div>
  );
};
Enter fullscreen mode Exit fullscreen mode

Styled with Tailwind CSS with text, margin, and color

import SearchIcon from './icons/SearchIcon';

const App = () => {
  return (
    <div>
      Search<SearchIcon className="ms-2 text-blue-500" />
    </div>
  );
};
Enter fullscreen mode Exit fullscreen mode

Note: We can also use this pattern for other .svg images which may have additional styling requirements.

Conclusion

This pattern is simple, flexible, and free. If you found this valuable, or have a better pattern for icons, let me know!

Top comments (0)