How to open detail view on table row select in react.js?

Viewed 258

I have a table with multiple rows and when I select a row, I want to display detailed information about the selected item.

I make use of react-router-dom v6 and MUI's material table component. Below a prototype: enter image description here

I make use of routes to switch content on menu item click. The next thing is to open a detailed view, but I'm not sure what pattern to use. I was thinking of using routes, like a nested route, but I don't know how to pass the selected object to the detail view that shows the object in more details. Ofcourse there are multiple ways to do it, but don't know what's the best practice.

So what's the best practice to achieve this and how?

UPDATE

I can solve my problem like the snippet below. It works, but I don't really like this solution.


const App = () => {
  const [activeRow, setActiveRow] = useState({});
  return (
    <StrictMode>
      <Table setActiveRow={setActiveRow} />
      <Userdetails activeRow={activeRow} />
    </StrictMode>
  );
};
1 Answers

The best way to do this is using useParams() with a dynamic path

first, create a dynamic route path

Example code

<Route path="invoices" element={<Invoices />}>
      <Route path=":invoiceId" element={<Invoice />} />
</Route>

please note:

  • We just created a route that matches URLs like "/invoices/2005" and
    "/invoices/1998". The :invoiceId part of the path is a "URL param",
    meaning it can match any value as long as the pattern is the same

now you can invoiceID in your <Invoice> as the example

let params = useParams();
return <h2>Invoice: {params.invoiceId}</h2>;

for more details your can follow React Router V6 guide

Related