3

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?

Dennis Vash
  • 50,196
  • 9
  • 100
  • 118
Sapinder
  • 193
  • 2
  • 14
  • Please show a reproducible example, see [How do I ask a good question?](https://stackoverflow.com/help/how-to-ask), [How to create a Minimal, Reproducible Example](https://stackoverflow.com/help/minimal-reproducible-example). Show us a sandbox ([codesandbox](https://codesandbox.io/s/vanilla-react-template-irhcq)) with an svg, what you trying to style, what have you tried and what is not working. In StackOverflow we ask specific questions and not "optimal solutions" which is too broad for a question and depends on the project. – Dennis Vash Jul 15 '20 at 09:01
  • @DennisVash I've provided the codesandbox link. I'm looking to change the color of `logoBookmark` which I `import` in the JSX file. – Sapinder Jul 15 '20 at 09:22
  • Note that its not a minimal example, instead you should have just shown only the SVG without all the project around it. – Dennis Vash Jul 15 '20 at 09:35

1 Answers1

1

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

Dennis Vash
  • 50,196
  • 9
  • 100
  • 118