Reputation: 109
I am new to SolidJS and I am working on a project where I don't have to change the URL while changing the route.
For example, I would like to navigate to a different page without typing the path manually.
Upvotes: 0
Views: 586
Reputation: 13698
Solid router already behaves like that. It does not matter if you navigate to the target URL via link or by manually typing the path, the router will load the related component.
If you are not going to use SSR, make sure to use HashRouter
instead of Router
, otherwise you will have page not found error on page refresh because you will landing on a different page. Another solution would be returning the same SPA from the server, in that case, client side application will be loaded on a different page.
Here is a simple application:
import { A, Route, Router, HashRouter } from '@solidjs/router';
import { Component, JSX } from 'solid-js';
import { render } from 'solid-js/web';
const Layout: Component<{ children: JSX.Element }> = (props) => {
return (
<div>
<ul>
<li><A href='/'>Home</A></li>
<li><A href='/blog'>Blog</A></li>
<li><A href='/users'>Users</A></li>
</ul>
{props.children}
</div>
);
};
const Home: Component<{}> = () => <Layout>This is Home page!</Layout>
const Users: Component<{}> = () => <Layout>This is Users page!</Layout>
const Blog: Component<{}> = () => <Layout>This is Blog page!</Layout>
const NotFound: Component<{}> = () => <Layout>Not Found!</Layout>
function App() {
return (
<HashRouter>
<Route path="/" component={Home} />
<Route path="/users" component={Users} />
<Route path="/blog" component={Blog} />
<Route path="*404" component={NotFound} />
</HashRouter>
);
}
render(() => <App />, document.body);
Layout in not strictly necessary but the A
component requires you to keep it under a Route
component. See this answer for more details: https://stackoverflow.com/a/78245608/7134134
If you don't want to use URL at all, neither let the user change the URL path, then you don't need a router, just use a Switch
component. But you will be giving up any benefits that are brought by using a router, such as bookmarking, providing visual feedback to the user via URL etc.
Upvotes: 0