1

I have an object in which CSS file code is coming like a string. Like

{    
    css: ".button { color: green } .button:after { color: red }"
}

How can I load CSS as a string in my React Component?

6
  • If you are able to read that string just parse it, split it by '.' and also by '{' and '}' Commented Jul 31, 2021 at 11:58
  • you can append css together and put them inside a <style> tag to make them accessible; then add appropriate classes to elements you need Commented Jul 31, 2021 at 12:00
  • @SulemanAhmad eval() is for javascript code, not css Commented Jul 31, 2021 at 12:02
  • @Mhmdrz_A how can I put a string inside a style? can you please share a snippet of code? Commented Jul 31, 2021 at 12:02
  • 1
    @ZuhairNaqi, You can do something like this let c = { css: ".submit { color: green } .cancel { color: red }" }; let stl = document.createElement("style"); stl.innerText = c.css; document.body.append(stl); Commented Jul 31, 2021 at 12:05

1 Answer 1

1

Here is an example of putting css into style tag to be used later

Appending to documnet.head can pollute global css scope; so if that is problematic you can append style to the element you are rendering, therefore the style will be unmounted after component unmounted

function mountStyles ( stylesStr ) {
  const styleTag = document.createElement('style');
  styleTag.textContent = stylesStr;
  document.head.appendChild(styleTag);
}

const someCSS = ".button { color: green } .button:after { color: red } ";

test.addEventListener('click', ()=> {
  mountStyles(someCSS);
})
<span class='button'> imagniray button </span>
<button id='test' > Click me </button>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.