skip to Main Content

Is there any way to write inline css in string rather than object format?

I tried this but it obviously didn’t work:

<div style={"color:red;font-weight:bold"}> Hello there </div>

Why am I doing this?

I usually write some inline css first and once it looks good in the browser I copy paste that inline into my .scss file
but if I use objects I’ll first have to convert them into css format and then paste them into my file which would be really tedious

( Note: If it is not possible I’m also open to using a vscode extension which converts object into css )

2

Answers


  1. Don’t Use Object, Just use like this

    <div style="color:red;font-weight:bold"> Hello there </div>
    
    Login or Signup to reply.
  2. No, you can’t use a string instead, not without a workaround that may be more effort than it’s worth.¹ From the documentation:

    When using inline styles in React, you can use React.CSSProperties to describe the object passed to the style prop. This type is a union of all the possible CSS properties, and is a good way to ensure you are passing valid CSS properties to the style prop, and to get auto-complete in your editor.

    interface MyComponentProps {
      style: React.CSSProperties;
    }
    

    In the comments, Konrad pointed to this question, which has an answer linking to a tool that converts between the two formats.


    ¹ For instance, Konrad also found and linked to this blog post which shows code for a function that converts a string to an object at runtime. So you could do style={theFunction("your styles")}. But aside from unnecessary complication, that would involve re-converting the string on every render (unless you memoized it, which costs memory and even more complexity…). Still, it’s an option.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search