SVGs in React & Tailwind CSS — fill: "currentColor" not working

Viewed 2326

I'm trying to get an SVG to change color on dark mode with Tailwind CSS. This means I have to set the SVG's fill color using a class like text-white (which translates to --tw-text-opacity: 1; color: rgba(255, 255, 255, var(--tw-text-opacity)); in pure CSS). Then I can add another Tailwind class like dark:text-black, which should make the SVG black when the user enables dark mode.

However, even when the SVG is properly formatted to use fill: currentColor, the fill does not match the currentColor (the text color) of the parent element (an img tag).

What am I doing wrong?

HTML

<img
  className="w-auto h-12 mx-auto mt-12 text-black rounded-full p-x4 dark:text-white"
  src="/brand/cerebrum-full.svg"
/>

SVG

<style type="text/css">
    .currentColorFill{fill:currentColor !important;}
</style>
<g>
  <path
    className="currentColorFill"
    d="M284.6,124.1v-0.2c0-23.8,17.9-43.3,43.6-43.3c15.8,0,25.2,5.3,33,12.9l-11.7,13.5c-6.5-5.9-13-9.4-21.4-9.4
      c-14.1,0-24.3,11.7-24.3,26v0.2c0,14.3,9.9,26.3,24.3,26.3c9.6,0,15.4-3.8,22-9.8l11.7,11.8c-8.6,9.2-18.2,14.9-34.3,14.9
      C302.9,167.2,284.6,148.2,284.6,124.1z"
  />
  <path class="currentColorFill" d="M412.3,25.5h3.4v6c1.7-3.8,5-6.6,9.3-6.4v3.7h-0.3c-5,0-9.1,3.6-9.1,10.5v9.1h-3.4V25.5z"/>

</g>
1 Answers

(Self answer after figuring it out...)

This is happening because you're embedding the SVG using an image tag. I would recommend importing the SVG from a component using something like this svg-to-react-cli NPM package.

Let's say your SVG is called "AcmeLogo" and you have it saved as AcmeLogo.svg. Here are the steps to take to convert your AcmeLogo.svg file to a React component:

  1. Run npm install -g svg-to-react-cli in your terminal
  2. Run svgtoreact <PATH_TO_SVG> <PATH_TO_EXPORT_REACT COMPONENT> like so:
    • svgtoreact /path/to/AcmeLogo.svg /path/to/AcmeLogo.js

Now, import AcmeLogo.js into your React page and add your classes to the component, like so:

import AcmeLogo from "components/AcmeLogo.js";

<AcmeLogo className="w-auto h-12 mx-auto mt-12 text-black p-x4 dark:text-white" />

This should work! Now you can try changing from light to dark mode and you should see the fill color of your SVG change based on the text color.

Related