Home > front end >  React return Outlet component when I use render in route
React return Outlet component when I use render in route

Time:12-22

I am trying to use react-router with props id but it gave me this info:

Matched leaf route at location "/some-12" does not have an element. This means it will render an <Outlet /> with a null value by default resulting in an "empty" page.

I'm using "react-router-dom": "6" and "react": "^17.0.2"

//example Routes
import {Route, Routes } from "react-router-dom";
function App()
return(
   <>
   <Routes>
      <Route path="/about" element={<About />}/>
      <Route exec={true} path="/something" element={<Something/>}/>
      <Route exact={true} path="/something-:id"
             render={(props) => {
             <Some id={props.match.params.id} />;}}
       />
      <Route path="/contact" element={<Contact />}/>
   </Routes>
   </>```
//example Some
export default function Some({ id }) {
    return(
       <>
          <p>Some with id: {id}
       </>
    )}

Where I did mistakes?

CodePudding user response:

In react-router-dom version 6 the Route components render all the routed components on the element prop and there are no longer any route props, i.e. no history, location, or match.

Render the Some component on the element prop and use the useParams hook to access the id route match param. If path="/something-:id" doesn't work then try making the id its own path segment, i.e. path="/something/:id".

function App()
  return(
    <>
      <Routes>
        <Route path="/about" element={<About />}/>
        <Route path="/something" element={<Something/>}/>
        <Route path="/something-:id" element={<Some />} />
        <Route path="/contact" element={<Contact />}/>
      </Routes>
    </>
  );
}

...

import { useParams } from 'react-router-dom';

export default function Some() {
  const { id } = useParams();
  return(
    <>
      <p>Some with id: {id}
    </>
  );
}

CodePudding user response:

It might be that you missed a return statement in your element prop.

<Route exact={true} path="/something-:id"
             render={(props) => {
             return <Some id={props.match.params.id} />;}}
       />
// or

<Route exact={true} path="/something-:id"
             render={(props) => <Some id={props.match.params.id} />;}/>

Note: Upon further research, the render prop has been removed in v6. You should use element instead and fetch the :id as per Drew Reese's answer

  • Related