despes de todos estos retos de este buen curso he decidido aceptar un reto: hacer el curso de react router DOM5
Fundamentos de navegación en la web
¿Cuándo necesitas React Router?
SSR vs. Single Page Applications
Versiones de React Router: ¿Por qué son tantas? ¿Cuál elegir?
Introducción a React Router DOM 6
Instalación de React Router DOM 6
BrowserRouter vs. HashRouter
Route: componentes de navegación
Link vs. NavLink
useParams: rutas dinámicas
useNavigate: historial de navegación
Outlet: nested routes
Fake authentication con React Router DOM 6
useAuth: login y logout
Menú con rutas públicas y privadas
Navigate y redirects: protegiendo rutas privadas
Roles y permisos
Reto: composición de componentes con navegación
Reto: UX de login y logout
Reto: roles complejos
React Router en TODO Machine
Integrando React Router a proyectos en React
Creando las rutas de TODO Machine
Botón de editar TODOs
Generador automático de IDs
Cambiando modales por navegación
Obtener y editar TODOs
useLocation: transferencia de datos por navegación
Deploy con React Router en GitHub Pages
Próximos pasos
Reto: página de búsquedas con navegación
Reto: TODO Machine con React Router DOM 5
Reto: PlatziMovies con React Router
Reto: crea tu propio React Router
Espera más cursos de React.js
No tienes acceso a esta clase
¡Continúa aprendiendo! Únete y comienza a potenciar tu carrera
Aportes 3
Preguntas 0
despes de todos estos retos de este buen curso he decidido aceptar un reto: hacer el curso de react router DOM5
Lo logré! Creé mi propio Router, con link y la posibilidad de usar HashRouter.
Al momento de comentar, no hay ninguna solución en los comentarios. Los invito a que prueben el reto! Y si ya lo hicieron, a que lo compartan.
Fue un muy buen reto. Casi me rindo muchas veces, pero finalmente lo terminé. Dejo mi solución.
import { useState } from 'react'
import { PathContext } from './Context'
export function Router({ children }) {
const [currentPath, setCurrentPath] = useState(window.location.pathname)
const routes = []
const navigate = to => {
window.history.pushState({}, '', to)
setCurrentPath(to)
}
return (
<PathContext.Provider
value={{ currentPath, setCurrentPath, routes, navigate }}
>
{children}
</PathContext.Provider>
)
}
import { useContext } from 'react'
import { PathContext } from './Context'
export function Route({ path, element }) {
const { currentPath, routes } = useContext(PathContext)
//Push all routes except '*' (not found) to routes[]
const routeInRoutes = routes.includes(path)
if (!routeInRoutes && path != '*') routes.push(path)
//returning in match
if (currentPath == path) return element
// Not found case
const currentPathInRoutes = routes.includes(currentPath)
if (path == '*' && !currentPathInRoutes) return element
}
import { useContext } from 'react'
import { PathContext } from './Context'
const styles = {
textDecoration: 'underline',
color: 'blue',
cursor: 'pointer',
}
export function Link({ to, children }) {
const { navigate } = useContext(PathContext)
return (
<a style={styles} onClick={() => navigate(to)}>
{children}
</a>
)
}
import { useState } from 'react'
import { PathContext } from './Context'
export function HashRouter({ children }) {
const windowPath = window.location.pathname.replace(/^\/#/, '')
const [currentPath, setCurrentPath] = useState(windowPath)
const routes = []
const navigate = to => {
window.history.pushState({}, '', `/#${to}`)
setCurrentPath(to)
}
return (
<PathContext.Provider
value={{ currentPath, setCurrentPath, routes, navigate }}
>
{children}
</PathContext.Provider>
)
}
import { createContext } from 'react'
export const PathContext = createContext()
import { Link } from '../router/Link'
import { Route } from '../router/Route'
import { Router } from '../router/Router'
export function App() {
return (
<Router>
<Route element={<HomePage />} path="/" />
<Route element={<BlogPage />} path="/blog" />
<Route element={<NotFound />} path="*" />
</Router>
)
}
function HomePage() {
return (
<>
<h1>You are in the home</h1>
<Link to="/blog">Go to blog</Link>
<p></p>
<Link to="/random-link">Go to non-existent page</Link>
</>
)
}
function BlogPage() {
return (
<>
<h1>You are in the blog</h1>
<Link to="/">Back to home</Link>
</>
)
}
function NotFound() {
return (
<>
<h1>Page not found</h1>
<Link to="/">Go to home</Link>
</>
)
}
import { Link } from '../router/Link'
import { Route } from '../router/Route'
import { HashRouter } from '../router/HashRouter'
export function AppWithHash() {
return (
<HashRouter>
<Route element={<HomePage />} path="/" />
<Route element={<BlogPage />} path="/blog" />
<Route element={<NotFound />} path="*" />
</HashRouter>
)
}
function HomePage() {
return (
<>
<h1>You are in the home</h1>
<Link to="/blog">Go to blog</Link>
<p></p>
<Link to="/random-link">Go to non-existent page</Link>
</>
)
}
function BlogPage() {
return (
<>
<h1>You are in the blog</h1>
<Link to="/">Back to home</Link>
</>
)
}
function NotFound() {
return (
<>
<h1>Page not found</h1>
<Link to="/">Go to home</Link>
</>
)
}
Todo se ve tan fácil y obvio una vez terminado jajaja… para nada se sintió así. Como siempre, tuve que volver a revisar todo mi conocimiento, consultar muchas fuentes y probar mil cosas.
Hola todos! Resultado del reto. Cualquier feedback es bienvenido.
Link del repositorio: https://github.com/jp-cortes/navigation-react
¿Quieres ver más aportes, preguntas y respuestas de la comunidad?
o inicia sesión.