Home > Software design >  How to server-side render a specific route in ReactJS?
How to server-side render a specific route in ReactJS?

Time:08-05

I would like to server-side render only a specific route in React. For example, /home should be client-side rendered, but /post should be server-side rendered.

The /post route receives a post ID as a parameter(using react-router) and fetches the content from a database server.

Is their any way I can server-side render only a specific page/route using react-dom server?

CodePudding user response:

Your data should be handled by the middleware and stored there to minimize api calls. The Front end should render based on that data.

CodePudding user response:

One good approach is to use built version of your react within express.js server. So let's say you have your built version of your react inside build directory :

var express = require('express');
var app = express();

app.use("/post",function(req,res) { 
   console.log(req); // Do your stuff for post route
});

app.use("/",express.static(path.join(__dirname,"/build")));
app.use("/*",express.static(path.join(__dirname,"/build"))); // Handle react-router

const httpServer = require("http").createServer(app);
httpServer.listen(8080, function(){
    console.log("Server is running on 8080");
});
  • Related