2

I am trying to generate static html from react using renderToStaticMarkup method. The problem I am facing right now is that I am not able to import css into react component. I want to import css in my React components like css-modules (import styles from './style.css'). And then inject that loaded css into generated static html head. How can I accomplish that?

P.S. I can't use webpack due to some constraints. If there is any babel plugin availabe for this specific case, then please let me know.

Here is how I am generating static html from react component:

const reactElement = require('react').createElement;
const ReactDomServer = require('react-dom/server');

const renderHTML = Component => {
  return ReactDomServer.renderToString(reactElement(Component))
}
1
  • If you have a static URL for the stylesheet, you could render a <link> tag. But if it has to go into <head> and you're not rendering that with React you'd need to resort to plain old JS to select the head element. Commented Sep 6, 2019 at 23:21

3 Answers 3

1

This may be challenging without a lot of custom logic.

If you want to inline the CSS only for the initial render and then fetch the rest after the initial render, styled-components may be a better option because it supports exactly what you're trying to achieve without too much configuration: https://www.styled-components.com/docs/advanced#server-side-rendering

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

1 Comment

I am generating static html only which will not have any JavaScript. It will be just plain html with internal styling. This is what I am not able to achieve. One plugin I found which might have worked for me (npmjs.com/package/babel-plugin-transform-import-css), but this plugin make use of load-styles package, which need document object. And in node env, that is not available.
1

You can pass a URL in as a prop and render a <link/> tag. Made an example here, not sure if that would meet your needs or if you need it to be a style tag.

Comments

0

May be I am too late you can also create It like this way.

React.createElement("style", {},[ "body {background-color: powderblue;}
h1   {color: blue;}
p    {color: red;}" ])

Output: 


  <style>
     body {background-color: powderblue;}
    h1   {color: blue;}
    p    {color: red;}
    </style>

Since createElement take 3 params and last one is children we can put our vanila css inside it as a children. You can put any imported file in the form of string and it will convert to style tag

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.