Styling svg in React with Sass

Viewed 716

I've done my previous 2 projects with React and had used Sass files for styling the components. But in this project it's getting a bit confusing because I've to use SVGs for my images. Now I'm stuck at styling SVGs with Sass files.

Here's the codesandbox including just the navbar component where I want to change the color of logoBookmark svg.

I don't want to paste the whole xml stuff. So I import the SVG straight away

import logoBookmark from "../../images/logo-bookmark.svg",

and set src={logoBookmark} for img tag.

To style external SVGs, I found this simple solution on stack overflow.

But I don't know how implement to this in React where I've a Sass file which is further imported in a JSX file.

So could someone please share the optimal solution for this problem?

1 Answers

You need to import the SVG as a component so it will mounted as <svg/> and not an <img/>. See adding SVG in CRA.

Then you just need to target the circle withing the svg with CSS:

.logo {
    circle {
        fill: red;
    }
}

import { ReactComponent as Logo } from "../../images/logo-bookmark.svg";

export default function NavBar() {
  return (
    <nav className="navbar">
      <div className="brand">
        <a href="/">
          <Logo className="logo" />
        </a>
      </div>
    </nav>
  );
}

Edit project1

Related