serverless-react-boilerplate icon indicating copy to clipboard operation
serverless-react-boilerplate copied to clipboard

Added React Router example configuration

Open arabold opened this issue 5 years ago • 5 comments

This adds React Router with full support for SSR.

arabold avatar Feb 02 '21 19:02 arabold

Hi there! I'm trying to implement Router with your boilerplate but there's been a major version change since this pull request & I'm getting various errors trying to implement. Is there a way to implement your boilerplate with Router v6 or should I just use v5 for now?

johncarmack1984 avatar Feb 02 '22 23:02 johncarmack1984

A while back I was using 6.0.0 Beta.0, so it's definitely possible to use the latest version, but you'll have to do some changes. I'll see if I find time to update the PR accordingly, but in the meantime, you can try:

  • There's no Switch router anymore. Follow the guidelines here by replacing your Switch with Routes: https://reactrouter.com/docs/en/v6/upgrading/v5#upgrade-to-react-router-v6. After this change, most of the code should work without problems but the server-side part.
  • In the server/render.tsx, the StaticRouter is exported from react-router-dom/server now and the location for StaticRouter needs to be constructed manually. Not sure if you still need the basepath or not:
    import { StaticRouter } from 'react-router-dom/server'
    
    // We need to build the request location string manually from the event path and the query string parameters
    let location: string = event.path
    if (event.queryStringParameters) {
      const searchParams = new URLSearchParams()
      Object.entries(event.queryStringParameters).forEach(([key, value]) => searchParams.append(key, value ?? ''))
      location += `?${searchParams.toString()}`
    }
    
    <StaticRouter location={location}>
      <App />
    </StaticRouter>
    

Hope that helps!

arabold avatar Feb 03 '22 15:02 arabold

Hmmmm okay! So I had V5 working last night, this morning I've tried to upgrade & implement those changes, and received this error:

ReferenceError: event is not defined

When I replace event with _event (as the variable is declared in the export statement in render.tsx) I get this error:

Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.

I'll keep working on other stuff while hoping for a solution :) thanks for your prompt response!

johncarmack1984 avatar Feb 03 '22 20:02 johncarmack1984

Figured it out!

Needed to change the import statement in server/render.tsx from:

import { StaticRouter } from "react-router-dom";

to:

import { StaticRouter } from "react-router-dom/server";

johncarmack1984 avatar Feb 03 '22 20:02 johncarmack1984