Created
April 13, 2017 09:09
-
-
Save pantharshit00/a4d971d08a092990a9a2f8d9f2c88f0f to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
}) | |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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