Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rendering React components with styles on the server

I'm using React for my components, and in order to package up the styles with my components, I'm requiring them in as per the documented webpack method: require('./style.css'); But when I try to render on the server, node-jsx throws an error when it attempts to transform the css. Is there another way of transforming the jsx which won't break on css? I'd rather not break the styles out into their own pipeline as that would defeat the advantage of webpack packaging components up nicely.

like image 771
user2309185 Avatar asked Jan 11 '15 23:01

user2309185


People also ask

Can React be rendered on server-side?

Yes! This is where server-side rendering for React comes in. In this article, I want to introduce you to server-side rending (SSR) with React, reasons to use it, and some popular frameworks for rendering React on the server side.

Which class in React allows you to render your components on the server?

Introduction. Server-side rendering (SSR) is a popular technique for rendering a client-side single page application (SPA) on the server and then sending a fully rendered page to the client. This allows for dynamic components to be served as static HTML markup.

How can you render different things on the server and client while working with hydrate () in React?

If we intentionally need to render something different on the server and the client, we can do a two-pass rendering. Components that render something different on the client can read a state variable like this. state. isClient , which can be set to true in componentDidMount() .


2 Answers

This can be solved setting webpack's "target" configuration to "node".

This simple example app should explain it clearly.

https://github.com/webpack/react-webpack-server-side-example/blob/master/webpack.config.js

like image 140
maletor Avatar answered Sep 18 '22 07:09

maletor


You could use require.extensions like this:

require.extensions['.css'] = function() {return null}
like image 37
Nick Dima Avatar answered Sep 22 '22 07:09

Nick Dima