UI developer tutorials and guides

Tuesday, June 14, 2022

Dynamic routes and params in Solidjs

 This example based on solid-app-router library. Dynamic routes are those route which are similar to /user/1 /post/79 /tag/tag-name

Note the value 1 and 79 these are used to access particular data from backed. In our case the post with id 79 or user with id 1. These value called parameters.

So how do we setup a dynamic route in Solidjs ?

<Route path='/posts/:id' element={<div>this is a dynamic route </div>}/>

Here we used :id to pass a parameter to the route. In Nuxtjs / Nextjs we used [id].js to deal with dynamic route, in Solidjs we can achieve this in Router definition.

How to access the params ? 

We have to read params from the Route component, it can be arrow function as follows.

import { useParams } from "solid-app-router";
()=>{
const route= useParams()
;}

 Then we can pass the value to the component, the complete Route definition will look like as follows.

<Routes>
<Route path='/' element={Home}/>
<Route path='/posts/:id' element={()=>{
const route= useParams();
return(<SinglePost id={route.id}/>)}}/>
</Routes>

 

0 comments:

Post a Comment