본문 바로가기
tech documents/memo

[React] StaticRouter

by kimtahen 2020. 7. 12.
반응형
app.get('/*', (req, res) => {
  const context = {};
  const app = ReactDOMServer.renderToString(
    <StaticRouter location={req.url} context={context}>
      <App />
    </StaticRouter>
  );
});

The StaticRouter component expects a location and a context prop. We pass the current url (Express’ req.url) to the location prop and an empty object to the context prop. The context object is useful to store information about a specific route render, and that information is then made available to the component in the form of a staticContext prop.

 

https://www.digitalocean.com/community/tutorials/react-react-router-ssr 

 

Using React Router 4 with Server-Side Rendering | DigitalOcean

A look at configuring React Router v4 to work with an Express server-side rendering setup. You'll see how to make use of StaticRouter and matchPath, among others.

www.digitalocean.com

import React from 'react';
import {renderToString} from 'react-dom/server';
import {StaticRouter} from 'react-router';
import express from 'express';
import App from '../src/App';

const app = express();

app.get('/*', (req, res) => {
    const context = {};
    const html = renderToString(
        <StaticRouter location={req.url} context={context}>
            <App/>
        </StaticRouter>
    );

    if (context.url) {
        res.writeHead(301, {
            Location: context.url
        })
        res.end();
    } else {
        res.write(`
        <!doctype html><div id="app">${html}</div>`)
        res.end();
    }
})

app.listen(8080, ()=>{
    console.log('Listening on 127.0.0.1:8080');
});

StaticRouter에서 context가 어떠한 원리로 작동하는 가에 대해 더 알아볼 예정이다.

반응형

'tech documents > memo' 카테고리의 다른 글

[Java] 클래스  (0) 2020.07.29
[Gatsby] gatsby develop 오류  (0) 2020.07.28
[React] react-router-dom  (0) 2020.07.11
[React] Immutable.js 활용한 onClick event  (0) 2020.07.10

댓글