Server Side Rendering and ReactJS.NET
See original GitHub issueWe’re currently working on a project which uses ReactJS.NET to render our React components server side, and then our client bundle takes over on the frontend once loaded.
Our styled components work perfectly client side, but we’re unable to get them working server side. All the examples we can see create a stylesheet using ServerStyleSheet
and then render the results to html…but we can’t do this in the .NET environment. Is there another way?
We tried the following which has some success on the server, but when the client takes over we lose all styles (and we’re not actually sure why it’s working since we don’t run collectStyles
on the sheet
):
// ServerApp.js
const generateStyles = () => {
const sheet = new ServerStyleSheet()
return sheet.getStyleElement()
}
const ServerApp = (props) => {
const styleTags = generateStyles()
return (
<Provider store={configureStore(props.initialState)}>
<StaticRouter location={props.path} context={props.context}>
{styleTags}
<App />
</StaticRouter>
</Provider>
)
}
The above only works when we include the following in our Babel config (but we lose styles when the js kicks in):
{
"plugins": [
["babel-plugin-styled-components", {
"ssr": true
}]
]
}
Are there any examples of using Styled Components with ReactJS.NET server side, or it is not even possible without renderToHtml
?
Thanks!
Issue Analytics
- State:
- Created 6 years ago
- Comments:7 (3 by maintainers)
@daveaspinall we have implemented full support for server-rendered styles, check it out here:
https://reactjs.net/features/css-in-js.html
@philpl okay, a quick update! We’ve managed to get our components working both server-side and client-side by forcing Styled Components to always generate the client-side style tag.
Essentially it was checking to see if the server-side
<style>
tag had been created, it found one in the DOM so didn’t create a new one, then the<style>
tag inside the page content is removed so we’re left with no styles.It’s hacky but we got it working by adding this on line 152 of
src/models/BrowserStyleSheet.js
:Obviously it’s not optimal but it gets around our problem until #1102 gets resolved.