Per "recuperare la rotta" in React con TypeScript suppongo tu voglia ottenere informazioni sulla rotta corrente, ovvero il path attuale nella URL, o altre informazioni come parametri o query string.
User
ho un oggetto di questo tipo "export const listRoutes = {
LOGIN: "/",
MONITOR: "/monitor",
};
"
Come faccio a verificare che non mi trovi in queste rotte=?
Assistant
Perfetto, hai un oggetto listRoutes con le rotte definite e vuoi verificare che la rotta corrente NON sia una di queste.
Supponiamo che tu voglia fare qualcosa solo se la rotta corrente non è una di quelle elencate.
import { useParams } from 'react-router-dom';
function UserProfile() {
const params = useParams<{ id: string }>(); // qui specifichi i tipi per params
return <div>Id utente: {params.id}</div>;
}
Considerazioni su TypeScript
useLocation ritorna un oggetto Location che ha diversi campi (path, search, hash, state)
useParams può essere tipizzato per definire esattamente le chiavi che ti aspetti
Riepilogo rapido
tsx
import { useLocation, useParams } from 'react-router-dom';
function MyComponent() {
const location = useLocation();
const params = useParams<{ id: string }>();
console.log(location.pathname); // path
console.log(params.id); // parametro dinamico, se c'è
return <div>Path: {location.pathname}, Id: {params.id}</div>;
}
Se invece usi un altro sistema di routing fammi sapere!
import React from 'react';
import { useLocation } from 'react-router-dom';
import { listRoutes } from './path/to/listRoutes';
const MyComponent = () => {
const location = useLocation();
const currentPath = location.pathname;
// Verifica se la rotta corrente **non** è presente in listRoutes
const isNotInListRoutes = !Object.values(listRoutes).includes(currentPath);
if (isNotInListRoutes) {
return <div>Sei in una rotta NON inclusa in Login e Monitor</div>;
} else {
return <div>Sei in Login o Monitor</div>;
}
};
export default MyComponent;
Spiegazione
Object.values(listRoutes) prende tutti i path (["/", "/monitor"])
includes(currentPath) verifica se il path corrente è in quelle rotte
! nega il risultato, quindi true se non è in quelle rotte
Variante per TypeScript con tipo
Se vuoi un controllo più rigoroso con tipi:
ts
type ListRoutes = typeof listRoutes;
type RoutePath = ListRoutes[keyof ListRoutes]; // "/" | "/monitor"