SVGs and React

Photo by Ricardo Gomez Angel on Unsplash

What are SVGs? According to the MDN:

Scalable Vector Graphics (SVG) are an XML-based markup language for describing two-dimensional based vector graphics. As such, it’s a text-based, open Web standard for describing images that can be rendered cleanly at any size and are designed specifically to work well with other web standards including CSS, DOM, JavaScript, and SMIL. SVG is, essentially, to graphics what HTML is to text.

For my React portfolio, I decided to use SVGs for my logo instead of importing them as images to save memory. There are many ways to go about this, but my approach was to import the SVGs directly as components.

import { ReactComponent as Logo } from '../images/logo.svg';

Once this was done, I had to figure out a way to change the color of my logo, depending on what page the user was on. Since the background of my home page is dark, the logo needs to be white; and since the background of my about page is white, the logo needs to be black.

Finding the answer to this was a lengthy process, but implementing it was a very easy step! First, change the value of the fill attribute in the HTML of the SVG to “current.”

<svg width="64" height="64" viewBox="0 0 64 64" fill="current" xmlns="http://www.w3.org/2000/svg">    <path d="M13..." fill="current"/>    <path d="M51..." fill="current"/>    <path d="M59.9..." fill="current"/></svg>

Now I can use the useState and useEffect Hooks to keep track of my logo color and window location! If the page is on /about, the logo will be black. Otherwise, the logo will stay white!

const [logoColor, setLogoColor] = useState("#FEFEFE")const location = useLocation()useEffect(() => {    switch (location.pathname) {        case "/about":            setLogoColor("#636363")        return logoColor        default:            setLogoColor("#FEFEFE")        return logoColor    }}, [location])

Now, remember when we imported our logo as a React component? When we call the component, all we would have to do to change the fill is to specify the value in the attribute.

<Logo fill={logoColor} />

Et voila!

--

--

--

Laotian-American woman pursuing my passion for mentally stimulating and complex problem-solving through programming.

Love podcasts or audiobooks? Learn on the go with our new app.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Chindalath Traymany

Chindalath Traymany

Laotian-American woman pursuing my passion for mentally stimulating and complex problem-solving through programming.

More from Medium

How to style React

React Components and Props

Prop Types in React

React JSX in Depth…