0

Is there any way to set an inline style in React without using CSSProperties?

I'm importing a bunch of SVGs that have styles defined inline in the regular fashion, with things like

style="fill:#bfd9ff;"

To convert that to work in React, right now I'm changing it to:

style={{fill: "#bfd9ff"}}

The thing is.. this is kind of a pain to do, even with regex (since not everything is the same format). I really wish I could just keep the strings as-is and not have to manually change each style attribute to a CSSProperties object.

Is there an alternate attribute or something that I could use to make it easier?

I'm imagining something like styleString="fill:#bfd9ff" where setting that attribute would fill in the style tag of the generated DOM element with the provided string, because then I could just do a quick replace of style to styleString. But I've done a bit of searching and can't seem to find anything like this, is there no other way than to just manually set up all the styles?

1
  • 1
    You could write your own function to convert a string like this to the required object - but it wouldn't be particularly pleasant. I'm not sure why it's any more of a "pain" to type the correct form than the string form - unless of course you're doing a mass copy-paste exercise, perhaps from an existing CSS file? Commented Jun 9, 2020 at 23:07

1 Answer 1

1

Have you tried importing your svgs as components? That way you could keep them in .svg files and you can keep the usual style=... syntax.

// importing a logo SVG and embedding it in JSX
import { ReactComponent as Logo } from './logo.svg';
const MyComponent = () => {
  return (
     ...
     <Logo />
  );
}

See: https://medium.com/@rossbulat/working-with-svgs-in-react-d09d1602a219

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.