Html-react-parser: Export cssToJs

Created on 29 Oct 2020  ·  5Comments  ·  Source: remarkablemark/html-react-parser

I'm trying to find a library to convert inline css string to React css style object. Example:

"background-color: blue; margin-top: 10px"

to:

{
backgroundColor: 'blue',
marginTop: '10px'
}

I understand that this is what cssToJs function does. And since I anyway use this library , it would be great if this function could be exported. I guess in a separate module, like attributesToProps, would be best.

dependencies

Most helpful comment

I moved cssToJs to another package style-to-js in #182

So in v0.14.2:

# npm
npm i [email protected]

# yarn
yarn add [email protected]

It will install the dependency style-to-js so you can do the following:

const styleToJS = require('style-to-js').default;

styleToJS('background-color: #BADA55', { reactCompat: true });

Let me know if this helps. You can check out the style-to-js README for more details.

All 5 comments

Agreed. I basically copied it out of these repo to use and I'm not happy about doing it that way. Would be great if it was just exported.

I moved cssToJs to another package style-to-js in #182

So in v0.14.2:

# npm
npm i [email protected]

# yarn
yarn add [email protected]

It will install the dependency style-to-js so you can do the following:

const styleToJS = require('style-to-js').default;

styleToJS('background-color: #BADA55', { reactCompat: true });

Let me know if this helps. You can check out the style-to-js README for more details.

That’s awesome. Thanks!

@christianfredh Let me know if there's anything else that you need. Otherwise, can you please close this issue?

I've tested it now and it works great, thank you!

I still need this helper function to check for null/undefined at the moment:

function cssToJs(style?: string | null) {
  return styleToJS(style ?? '', { reactCompat: true })
}

I see there is a check for this in the actual code which returns an empty object. Maybe that could be reflected typescript-wise as well, I don't know. Either way, it works great, and I will close the issue.

Was this page helpful?
0 / 5 - 0 ratings