Search code examples
reactjsreact-router-dom

React router dom only re-render a component on page on dynamic routes


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?


Solution

  • You could create a ChatLayout component which will have all the Navbar , Sidebar components which you want to reuse and not re-render on change in chat-id.
    Then create a nested route like

    <Route path="/" element={<RootLayout />}>
      <Route index element={<Landing />} />
      <Route path="auth" element={<Auth />} />
      <Route path="chat" element={<ChatLayout />}> 
        <Route path=":id" element={<MainPanel />}>
      </Route>
    </Route> 
    

    ChatLayout

    const ChatLayout = () => {
      return (
        <>
          <Navbar />
          <Sidebar />
          <Outlet />
        </>
      );
    };
    

    MainPanel

    const MainPanel = () => {
      const { id } = useParams();
      return <h1>MainPanel - chat id - {id}</h1>;
    };
    

    Inside the MainPanel you can use the useParams() hook to get the id.
    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