Skip to content

Instantly share code, notes, and snippets.

@pantharshit00
Created April 13, 2017 09:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pantharshit00/a4d971d08a092990a9a2f8d9f2c88f0f to your computer and use it in GitHub Desktop.
Save pantharshit00/a4d971d08a092990a9a2f8d9f2c88f0f to your computer and use it in GitHub Desktop.
import express from 'express';
import {renderToString} from 'react-dom/server';
import React from 'react';
import Component from './react-router.jsx';
import {StaticRouter as Router} from 'react-router-dom';
const app = express();
function template(data){
return `
<html>
<head>
<title>Server Side Rendering</title>
</head>
<body>
<div id="app">${data}</div>
</body>
</html>
`;
}
app.get("/*",(req,res)=>{
let context={};
let rendered = template(renderToString(<Router location={req.url} context={context}><Component /></Router>));
res.send(rendered);
});
const PORT = 3000;
app.listen(PORT,()=>{
console.log("http://localhost:"+PORT);
})
import React from 'react';
import ReactDOM from 'react-dom';
import {BrowserRouter as Router,Link,Route} from 'react-router-dom';
export default class App extends React.Component{
render(){
return(
<div>
<ul>
<li><Link to="/">Home</Link></li>
<li><Link to="/about">About</Link></li>
</ul>
<hr/>
<Route exact path="/" component={Home} />
<Route path="/about" component={About} />
</div>
)
}
}
//State less components
//Home
const Home = ()=> (
<div>
<h1>Home</h1>
<p>This is the Home Page</p>
</div>
)
//About
const About = ()=>(
<div>
<h1>About</h1>
<p>This is about</p>
</div>
)
if(typeof window !== "undefined")
ReactDOM.render(<Router><App /></Router>,document.getElementById('app'));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment