Home > front end >  Render React page dynamically using URL parameter
Render React page dynamically using URL parameter

Time:05-01

I've got a page at <url>/machines which lists the IP addresses of a set of machines on a network. I want to be able to click on one in the list and link to a page <url>/machines/<machineid> to render a new page which which show information about that specific machine. I want the value specified in the URL as <machineid> to be passed into the rendered page as a usable value, e.g. in a prop/param etc.

I'm having trouble configuring react router to achieve this, and am wondering if anyone can see what I'm doing wrong? I've been following the React Router V6 docs, however can't seem to get it to work. When I render the page at <url>/machines/hello, I get a console error saying No routes matched location "/machines/hello". Can anyone see what I'm doing wrong?

I was initially thinking I'd just render a new page (using a different component) to render the Machine Info page, however looking at the React Router V6 docs, it seems like the <MachineInfo> component is now rendered as a child of <Machines>?

I have an alert() in the <MachineInfo> component which doesn't seem to be being run at all. I get no alert.

App.js

function App() {
  const value = useContext(Context);
  return (
    <div className="App">
      <Routes>
        <Route path="/" element={<Dashboard />} />
        <Route path="machines" element={<Machines />}>
          <Route path="machines/:id" element={<MachineInfo />} />   // I've tried this using just path=":id" as well with no luck
        </Route>
        <Route path="topology" element={<Topology />} />
        <Route path="settings" element={<Settings />} />
      </Routes>
    </div>
  );
}

MachineInfo.js

export default function MachineInfo(props) {

    const [state, dispatch] = useContext(Context);
    let { id } = useParams<"id">([]);
    alert("info: "   id)
    
    return (
        <p>hello</p>
    );
}

CodePudding user response:

First, you'll want a Layout component that will have your Outlet

export function Layout() {
  return (
    <>
     <Outlet />       
    </>
  );

Now wrap your other routes within this Layout component & you'll notice you can now get to your nested route by saying /machines/1 The Dashboard component is the index so / should match this route.

function App() {
  // Not sure why you have value since it doesn't seem to be getting used
  const value = useContext(Context);
  return (
    <div className="App">
      <Routes>
        <Route path="/*" element={<Layout />}>
           <Route index element={<Dashboard />} />
           <Route path="machines" element={<Machines />}>
             <Route path=":id" element={<MachineInfo />} />   
           </Route>
           <Route path="topology" element={<Topology />} />
           <Route path="settings" element={<Settings />} />
         </Route>
      </Routes>
    </div>   
   );
 }
  • Related