Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use inline style in React with plain CSS string

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?

like image 309
Jan Schaefer Avatar asked Oct 25 '15 15:10

Jan Schaefer


People also ask

Can We Use inline CSS in React?

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.

Can you use regular CSS with React?

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.

Why not use inline styles React?

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.


2 Answers

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.

like image 94
raystubbs Avatar answered Oct 16 '22 14:10

raystubbs


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>
like image 37
Wesley Ricardi Avatar answered Oct 16 '22 14:10

Wesley Ricardi