Estoy intentando crear algunas rutas en mi aplicación web usando react-router . Sin embargo, algunas páginas necesitan compartir componentes, como la Navigation o el Footer de página, donde otras no lo hacen.
Básicamente, lo que necesito es una forma de verificar si una ruta no coincide con algunas ubicaciones preestablecidas y, si no, representa el contenido.
En este momento estoy haciendo esto así:
const displayComponentIfAllowed = (location, component) => { const C = component; const globalComponentsDisallowedPaths = ["/booking"]; // If the path matches something within the blocked list, then return null. let allowToRender = true; globalComponentsDisallowedPaths.forEach(disallowedPath => { if(location.pathname === disallowedPath){ allowToRender = false; } }); // Otherwise, return component to render. return allowToRender ? <C /> : null; } return ( <Router> <Routes> <Route render={({ location }) => displayComponentIfAllowed(location, Navigation)} /> <Route path="/"> <Route index element={<Home />} /> <Route path="booking/:customer_id" element={<Booking />} /> </Route> <Route render={({ location }) => displayComponentIfAllowed(location, Footer)} /> </Routes> </Router> ); Sin embargo, desde que se introdujo V6 de react-router-dom , esto no parece funcionar. Me imagino que esto se debe a que el render prop ha quedado obsoleto (aunque no estoy seguro, pero no se menciona en los documentos).
¿Hay alguna solución alternativa, o una mejor implementación de esto que funcione con V6 ? Salud
Cree un componente de diseño que represente los componentes de la interfaz de usuario que desea y un Outlet para que se representen las rutas anidadas.
Ejemplo:
import { Outlet } from 'react-router-dom'; const HeaderFooterLayout = () => ( <> <Navigation /> <Outlet /> <Footer /> </> );...
import { BrowserRouter as Router, Routes, Route } from "react-router-dom"; ... <Router> <Routes> <Route element={<HeaderFooterLayout />} > <Route path="/"> <Route index element={<Home />} /> ... other routes you want to render with header/footer ... </Route> </Route> <Route path="booking/:customer_id" element={<Booking />} /> ... other routes you want to not render with header/footer ... </Routes> </Router>