I’m currently working on a chat application.
Currently in my App.tsx
, I have the following.
<Route path="/" element={<RootLayout />}>
<Route index element={<Landing />} />
<Route path="auth" element={<Auth />} />
<Route path="chat" element={<Chat />} />
</Route>
In my Chat.tsx
, I have a Navbar
, Sidebar
, and MainPanel
component. How can I modify this so that the chat route takes an id parameter, and depending on the id of the chat, I re-render just the MainPanel
component to update the chat (since the MainPanel
component is the one displaying the conversations) rather than re-rendering the entire Chat
component?
2
Answers
use useParams.
You can get id by using
useParams()
, pass it like<Route path="chat/:id" element={<Chat />} />
If you wanna play around with code.
You could create a
ChatLayout
component which will have all theNavbar
,Sidebar
components which you want to reuse and not re-render on change inchat-id
.Then create a nested route like
ChatLayout
MainPanel
Inside the
MainPanel
you can use theuseParams()
hook to get theid
.Note you should do all your routing and navigation using either
useNavigate()
hook or the<Link to="route-to-navigate"> route name</Link>
For more detailed info regarding the above hooks and
<Outlet/>
you should checkout the react-router documentation of the version you are using. They have decent tutorials and examples to get started.If you want to checkout the code , I have created a sample sandbox here