React Router v6 – useLoaderData in server-side rendered application

  Kiến thức lập trình

I have a server-side rendered app organized in very much the same way as follows:

App.tsx

export default function App() {
    return (
      <html>
        <head>
          <title>Server Rendered App</title>
        </head>
        <body>
          <Routes>
            <Route path="/" element={<div>Home</div>} />
            <Route path="/about" element={<div>About</div>} />
          </Routes>
          <script src="/build/client.ts" />
        </body>
      </html>
    );
}

server.ts

import express from "express";
import ReactDOMServer from "react-dom/server";
import { StaticRouter } from "react-router-dom/server";
import App from "./App";

let app = express();

app.get("*", (req, res) => {
    let html = ReactDOMServer.renderToString(
      <StaticRouter location={req.url}>
        <App />
      </StaticRouter>
    );
    res.send("<!DOCTYPE html>" + html);
});

client.ts

import * as ReactDOM from "react-dom";
import { BrowserRouter } from "react-router-dom";
import App from "./App";

ReactDOM.hydrate(
    <BrowserRouter>
      <App />
    </BrowserRouter>,
    document.documentElement
);

Now, I want to be able to use the loader pattern and the useLoaderData hook provided by react-router in order to fetch data and make it available to the underlying component – in other words, to be able to pass data from server-side route fetching to the component.

However, all of the tutorials and examples that I see use createBrowserRouter but I’m not sure how to go about integrating that with my existing application.

Is there a way to directly use the loader pattern and useLoaderData in my application as it currently stands or can anyone instruct me on how to go about migrating my SSR app to support something like createBrowserRouter?

LEAVE A COMMENT