Jack
Jack

Reputation: 157

How to render server side react content with NextJS and React Router?

I need to render my React app from the server side. For that, i am using the framework next.js. But i am facing two issue.

First, i need to serve my app dynamically. That means i need a server side router to display my react components according to the current url.

Then, i need to load some dynamic data before render my components. So i need to pass these data from node to my react component.

this is my current situation :

// In Node.js

app.get("/",function(req,res){

  return app.prepare()
    .then(() => handle(req, res))
    .catch(ex => {
      console.error(ex.stack)
      process.exit(1)
    })
})

//In React.js

import React from 'react'
export default class Index extends React.Component{
 
  render(){
    return(
      <div>
        <p>Hello Server Side Rendered React App from Google Cloud Front</p>
        
      </div>
    )
  }
}

So , What should i do ?

Upvotes: 2

Views: 493

Answers (1)

diegochavez
diegochavez

Reputation: 662

If you are using NextJs with React, you don't need react-router to create pages, is easier, you need to create a directory named pages with component called index.js, they have components to manage navigation and so on.

Take a look at GitHub docs they already covered these steps really well.

https://zeit.co/blog/next2

Quick example:

// pages/index.js
import Link from 'next/link'
export default () => (
  <div>Click <Link href="/about"><a>here</a></Link> to read more</div>
)

// pages/about.js
export default () => (
  <p>Welcome to About!</p>
)

Upvotes: 1

Related Questions