React Router can be used in two different modes:
→ We used that in chapter 05
$ npx create-react-router@latest my-react-router-app
? Initialize a new git repository?
> Yes
? Install dependencies with npm?
> Yes
$ cd ./my-react-router-app
$ npm run dev
Folder structure
index() indicates an index route
→ URLs / and /concerts
Static route segments
→ e.g. /about and/concerts/trending
Routes can be nested inside parent routes (e.g. layout,route).
→ URLs /login (layouts don't add any segments to the URL)
Dynamic route segments (parameters) start with :
→ e.g. /concerts/schlieren
blog.$slug.tsx
Return a Response object…
…or throw it!
root.tsx
routes.ts
pages/list/ListPage.tsx
src\pages\details\DetailPage.tsx
Complete solution code can be found on GitHub on the branch chapter-10-framework-mode.
How can we redirect to a different route?
E.g. / → /blog
How can we redirect to a different route?
E.g. / → /blog
_index.tsx
Must be a named export called loader.
_index.tsx
→ redirects to blog.tsx
blog.$slug.tsx
Let's start simple: We can use a native HTML form.
blog.$slug.tsx
On the server the form is processed by an action.
blog.$slug.tsx
Form data is read from the request using the standard Request.formData() method.
blog.$slug.tsx
The data can then be processed as desired (validated, stored, etc.).
blog.$slug.tsx
Like the loader, the
action function can return a Response
object.
Typically, a redirect is returned to
implement the
Post/Redirect/Get
pattern.
blog.$slug.tsx
What will happen when the user clicks the Submit button?
→ It works! But it does a full document request: POST /blog/…
blog.$slug.tsx
The React-Router Form component together with the clientAction brings the expected SPA behavior
It still has the native form behavior as
long as JS has not loaded yet.
→ Progressive Enhancement
blog.$slug.tsx
The React-Router allows to access the generated types for typesafety on this level.
It also provides typse for actions and clientActions!
If unsure, go for client side rendering with framework mode (and clientLoaders)
We learned…