I am trying to achieve Server side rendering with my create-react-app project. I don't really need routes for now because it's a single-page application. I have been going through some articles but they seem to be quite complicated to me. Could someone guide me about how to do it or could link me to some simpler articles please?
Here is the code till now:-
The main app component, which imports other components:-
import React, { Component } from "react";
import HomePage from "./HomePage";
import "./App.css";
class App extends Component {
render() {
return(
<div>
<HomePage/>
</div>
);
}
}
export default App;
The Express code till now:-
import express from "express";
import React from "react";
import { renderToString } from "react-dom/server";
import App from "../src/App";
const app = express();
app.use(express.static("../public"));
app.get('*', (req, res) => {
res.send(`
<!DOCTYPE html>
<head>
<title>Universal React</title>
</head>
<body>
<div id="root">${renderToString(<App/>)}</div>
</body>
</html>
`);
});
app.listen(3000, () => {
console.log('Server running on PORT 3000');
})
All the articles or videos I have checked out till now use webpack and make changes to webpack.config.js file but I am using Create-react-app which comes with webpack included, there is no config file so I am a bit confused about how to make the required changes?
You have to eject the project/scripts/webpack config
Here's an example article on how to implement server-side rendering with react-router/redux
react-scripts
withreact-app-tools
package.json
to callreact-app build
,react-app start
src/index.js
tosrc/app.browser.js
, add one more entry point for the serversrc/app.node.js
Directory Layout
src/app.browser.js
src/app.node.js
package.json
More info: https://github.com/kriasoft/react-app