Home > Mobile >  How to change in a dynamic way a SVG fill color by passing props?
How to change in a dynamic way a SVG fill color by passing props?

Time:12-03

I have this rendered icon on my component:

<div
  style={{ cursor: 'pointer' }}
  onClick={() => setNewEntryVisible(true)}
>
  <PlusIconNoBorder color={selected.backgroundColor} />
</div>

Where I pass as a prop a color coming from the state and then the prop is passed to my icon file, where i use fill: color as follow:

import React from 'react'

function PlusIconNoBorder({color}) {
  return (
    <svg
      width="16"
      height="17"
      viewBox="0 0 16 17"
      fill="none"
      xmlns="http://www.w3.org/2000/svg"
    >
      <path
        fill-rule="evenodd"
        clip-rule="evenodd"
        d="M8.5 2.5C8.5 2.22386 8.27614 2 8 2C7.72386 2 7.5 2.22386 7.5 2.5V8H2C1.72386 8 1.5 8.22386 1.5 8.5C1.5 8.77614 1.72386 9 2 9H7.5V14.5C7.5 14.7761 7.72386 15 8 15C8.27614 15 8.5 14.7761 8.5 14.5V9H14C14.2761 9 14.5 8.77614 14.5 8.5C14.5 8.22386 14.2761 8 14 8H8.5V2.5Z"
        fill={color}
      />
    </svg>
  );
}

export default PlusIconNoBorder

I am not really sure why does not work, any clues? i tried to console.log(selected.backGrouldColor and it is correct. Not sure where the mistake lays

CodePudding user response:

Try this, this svg shows color in SVG tag.

import React from 'react'

function PlusIconNoBorder({color}) {
  return (
    <svg
      width="16"
      height="17"
      viewBox="0 0 16 17"
      fill={color} //<------- fill here
      xmlns="http://www.w3.org/2000/svg"
    >
      <path
        fill-rule="evenodd"
        clip-rule="evenodd"
        d="M8.5 2.5C8.5 2.22386 8.27614 2 8 2C7.72386 2 7.5 2.22386 7.5 2.5V8H2C1.72386 8 1.5 8.22386 1.5 8.5C1.5 8.77614 1.72386 9 2 9H7.5V14.5C7.5 14.7761 7.72386 15 8 15C8.27614 15 8.5 14.7761 8.5 14.5V9H14C14.2761 9 14.5 8.77614 14.5 8.5C14.5 8.22386 14.2761 8 14 8H8.5V2.5Z"
        fill={color}
      />
    </svg>
  );
}

export default PlusIconNoBorder

CodePudding user response:

Maybe jsx can help, have you tried ${color} enclosed in backticks ?

  • Related