Reputation: 1336
I would like to know is there any inbuilt function or something in react for converting SVG style attribute to JSX.
I have style like this:
'opacity:0.647;fill:#cbcbcb;fill-opacity:1;stroke:#cbcbcb;stroke-width:0.26458335;stroke-opacity:1'
I want to convert it into:
{{"opacity":"0.647","fill":"#cbcbcb","fillOpacity":"1","stroke":"#cbcbcb","strokeWidth":"0.26458335","strokeOpacity":"1"}}
Is there any easy way?
Upvotes: 1
Views: 1100
Reputation: 21
There's a vscode extension for this called "html to JSX"
Here's the link to the extension:
https://marketplace.visualstudio.com/items?itemName=riazxrazor.html-to-jsx
Just select all of your svg code and then press Ctrl + Shift + P -> Convert HTML to JSX
Upvotes: 0
Reputation: 1077
There's no built-in functionality for this. You may convert your styles string into an object using a simple reducer function, and then pass it as a prop.
const str =
"opacity:0.647;fill:#cbcbcb;fill-opacity:1;stroke:#cbcbcb;stroke-width:0.26458335;stroke-opacity:1";
const styles = str.split(";");
const svgStyles = styles.reduce((obj, item, i) => {
const [key, value] = item.split(":");
const updatedkey = key.replace(/-([a-z])/ig, s => s.slice(-1).toUpperCase());
obj[updatedkey] = value;
return obj;
}, {});
console.log(svgStyles);
Upvotes: 1
Reputation: 683
I am not sure there exists a React inbuilt tool for this. You could code this yourself and make your own quick tool to transform the syntax. Othwerise, if you don't want to use external websites, you can have a look at the svg-to-jsx module which can be used within your project or via command line
npm install svg-to-jsx
or svgr (https://github.com/gregberge/svgr) for SVG -> React component directly if you prefer
Upvotes: 3