Suppose you want to redirect paths beginning with @ to a specific user page. For example, the @datawookie path would take you to the user page for handle datawookie.
There are probably a few ways to do this, but one approach would be to use dynamic routing.
🚀 TL;DR
Show me the code. Look at the 27-dynamic-users branch. This site is deployed here.
First let’s set up the user page at src/pages/user.jsx.
import React from "react"
import Layout from "../layouts"
export default function User({ handle }) {
console.log(handle);
return (
<Layout>
<h1>User Page: {handle}</h1>
</Layout>
)
}
Nothing fancy there. The User component accepts a single argument, handle, which it interpolates into an <h1> tag.
Next we’ll set up dynamic routing via src/pages/[...].js.
import React from "react";
import User from "./user";
export default function DynamicRoute(props) {
const slug = props.params[`*`];
if (slug && slug.startsWith("@")) {
return (
<div>
<User handle={slug.slice(1)} />
</div>
);
}
}
The conditional checks whether there is an URL slug and that it starts with a @. When both of these conditions are satisfied it renders the User component.
That’s it. If you request a path beginning with an @ you’ll end up on a (spectacularly boring) user page.
Try this, which should get you to the page below.