Home > Net >  React: SVG dynamically add CSS by id or class
React: SVG dynamically add CSS by id or class

Time:10-27

In React I have a svg file such as mySVG.svg

<svg width="50" height="50" viewBox="0 0 50 50" xmlns="http://www.w3.org/2000/svg">
  <rect id="Unit1" class="class1" x="0" y="0" width="10" height="10" fill="blue"/>
  <rect id="Unit2" class="class1" x="10" y="10" width="10" height="10" fill="blue"/>
  <rect id="Unit3" class="class2" x="20" y="20" width="10" height="10" fill="blue"/>
</svg>

Then, in the component file Example.tsx, I would like to dynamically set the svg's colors based on passed in props

import  { ReactComponent as mySvg} from 'assets/mySVG.svg';

export function Example(props:{highlighted:string}):ReactElement {

  if (props.highlighted === 'Unit1') {  
    return (
      <mySvg
        //set unit 1 fill color to red
      />
    );
  }

  return (
    <mySvg />
  );
}

How would I accomplish dynamically setting the fill color of the svg based on id and className of the svg paths?

Importing a static css file with the colors defined won't work because I need this to work dynamically.

CodePudding user response:

You can manipulate the file you are importing, but I think the easiest way to do that is by creating your svg as a component.

See an example here: https://codesandbox.io/s/happy-galois-1tfce

CodePudding user response:

firstly, I would like to recommend this site to you, it converts ordinary svg code into a jsx component. It is enough for you to transfer the necessary props to the component with your svg mySVG.jsx :

import * as React from "react"

function mySVG({color = "#000000", className = "", width = 50, height = 50}) {
  return (
    <svg 
      className={className} 
      width={width} 
      height={height} 
      xmlns="http://www.w3.org/2000/svg"
    >
      <path fill={color} d="M0 0h10v10H0zM10 10h10v10H10z" />
      <path fill={color} d="M20 20h10v10H20z" />
    </svg>
  )
}

export default mySVG

and transfer the necessary data to your component with svg

import mySVG from "/you/path/mySVG"


// other code.... 


  return (
    <mySVG 
       color="#ffffff" 
       height={100} 
       width={100} 
       className="my-svg-style" 
    />
  );
  • Related