Solid Router: setup and routes
A router shows different components depending on the address in the browser: / is the home page, /posts the post list, /about the "About the blog" page. Moving between pages happens without a reload. The official router for Solid is the @solidjs/router package; the course covers version 0.15.
Installation
In the blog project folder, run:
npm install @solidjs/routerPages
Pages are ordinary components. They usually live in the src/pages folder:
// src/pages/Home.jsx
export default function Home() {
return <h1>Blog home</h1>;
}// src/pages/About.jsx
export default function About() {
return <h1>About the blog</h1>;
}Routes
Routes are described in the entry point, instead of rendering App directly:
// src/index.jsx
/* @refresh reload */
import { render } from 'solid-js/web';
import { Router, Route } from '@solidjs/router';
import './index.css';
import Home from './pages/Home';
import About from './pages/About';
render(
() => (
<Router>
<Route path="/" component={Home} />
<Route path="/about" component={About} />
</Router>
),
document.getElementById('root'),
);Open http://localhost:3000 — you see "Blog home", and at http://localhost:3000/about — "About the blog".
A shared layout and links
The header and menu are needed on every page. The component passed to the root attribute of Router wraps all pages, and the current page arrives in props.children. Make App the layout:
// src/App.jsx
import { A } from '@solidjs/router';
export default function App(props) {
return (
<>
<nav>
<A href="/" end>Home</A> | <A href="/about">About</A>
</nav>
<main>{props.children}</main>
</>
);
}In src/index.jsx add import App from './App'; and replace <Router> with <Router root={App}>. Now the menu is visible on every page, and clicking a link changes the content of main without a reload.
The A component
| Attribute | Purpose |
|---|---|
href | The page address |
activeClass | Class for the link to the current page, active by default |
end | Treat the link as active only on an exact address match |
Without end the link to / would be active on every page, because every address starts with /.
A 404 page
A route with * matches any address. Put it last:
// src/index.jsx
<Route path="*404" component={NotFound} />Create the NotFound component in src/pages/NotFound.jsx the same way as About. An address like /abc shows it.
Common mistake
Using a plain a tag for internal links. The link works, but the browser reloads the whole app and resets its state. For navigation inside the site use A from @solidjs/router.