I am rewriting an existing App which was based on AngularJS in ReactJS. In the App the user has the possibility to provide a CSS style string to style certain elements. In AngularJS this was no problem, I just set the 'style' attribute to the given string. In ReactJS I cannot do this anymore, because ReactJS requires a style object. I do not want to change the behavior of the application and require users to now provide a ReactJS compatible style object. Is there any way in ReactJS to just use a plain CSS style string to set the style of an element?
Achieving the same results with inline styles works quite differently. To use inline styles in React, use the style attribute, which accepts a Javascript object with camelCased properties.
You can style a React app with plain CSS, in plain . css files, just the same as you can style HTML (or Vue or Svelte or Angular) with plain CSS. Notice how we're import ing the CSS file on line 2, and then we can just use the CSS class on the button via the usual className prop.
You probably shouldn't use inline styles if: You feel that you may move away from React or have components you need to share in non-React projects. You aren't willing to take on a new dependency in the form of an inline-styling library. You have a lot of global styling to maintain.
This is a hack I found for reagent, but I believe it'll work equally well for raw react versions >= 16 (where custom dom attributes are passed threw). Just use the upper case STYLE
attribute instead of lower case style
, which is intercepted by React.
complementing taylor michels' answer
function CSSstring(string) {
const css_json = `{"${string
.replace(/; /g, '", "')
.replace(/: /g, '": "')
.replace(";", "")}"}`;
const obj = JSON.parse(css_json);
const keyValues = Object.keys(obj).map((key) => {
var camelCased = key.replace(/-[a-z]/g, (g) => g[1].toUpperCase());
return { [camelCased]: obj[key] };
});
return Object.assign({}, ...keyValues);
}
return <div style={CSSstring("margin-top: 4px; top: 100px")}></div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With