Route parameters and navigation
A route parameter is a variable part of the address, such as the post number in /posts/7. One route with a parameter serves all posts at once, and the component reads the parameter's value to show the right one.
A route with a parameter
A parameter is marked with a colon. Add routes in src/index.jsx next to the others:
// src/index.jsx
<Route path="/posts" component={Posts} />
<Route path="/posts/:id" component={Post} />Remember to import Posts and Post from the src/pages folder.
Reading the parameter
// src/pages/Post.jsx
import { useParams } from '@solidjs/router';
export default function Post() {
const params = useParams();
return <h1>Post number {params.id}</h1>;
}Open http://localhost:3000/posts/7 — you see "Post number 7". Parameter values are always strings.
params is a reactive object. When you go from /posts/7 to /posts/8, the component is not created again; params.id simply changes its value. So, as with props, read params.id where you need it instead of saving it in a variable.
Links to posts
The post list builds links with the number in the address:
// src/pages/Posts.jsx
import { For } from 'solid-js';
import { A } from '@solidjs/router';
const posts = [
{ id: 1, title: 'First post' },
{ id: 2, title: 'Second post' },
];
export default function Posts() {
return (
<ul>
<For each={posts}>
{(post) => (
<li>
<A href={`/posts/${post.id}`}>{post.title}</A>
</li>
)}
</For>
</ul>
);
}At http://localhost:3000/posts you see two links; a click opens the post page. In the next lesson the list will be loaded from the server.
Navigating from code
Sometimes you need to navigate after an action rather than through a link — for example, after deleting a post. That is what useNavigate is for:
// src/pages/Post.jsx
import { useParams, useNavigate } from '@solidjs/router';
export default function Post() {
const params = useParams();
const navigate = useNavigate();
return (
<div>
<h1>Post number {params.id}</h1>
<button onClick={() => navigate('/posts')}>Back to list</button>
</div>
);
}Clicking the button takes you back to the post list.
Other functions
| Function | What it returns |
|---|---|
useParams() | Path parameters: params.id |
useNavigate() | A navigation function navigate(address) |
useLocation() | The current address: location.pathname |
useSearchParams() | Parameters after ? and a function to change them |
Common mistake
Destructuring the parameters: const { id } = useParams(). The value is read once, and when you follow a link from post 7 to post 8, the page still shows number 7. Access params.id right in JSX and in functions.