React router component
Components in React Router V6
BrowserRouter
BrowserRouter is main component to cover our React application to make it routable.
/about) for navigation.
You can define the path and element which will be render according to that path
import { createBrowserRouter, RouterProvider} from "react-router-dom";
import App from './App.jsx'
const router = createBrowserRouter([
{
path: "/",
element: <App/>,
},
]);
ReactDOM.createRoot(document.getElementById("root")).render(
<React.StrictMode>
<RouterProvider router={router} />
</React.StrictMode>
);
useNavigate
Directly redirect to page to specific URL
import { useNavigate } from 'react-router-dom';
const navigate = useNavigate();
navigate('/another-page');
useParams
Used to access path parameters, we will learn this in next chapter (dynamic routing)
import { useParams} from 'react-router-dom';
let { id } = useParams();
useSearchParams
Used to get the query params in URL (some url might attach some data after "?" sign)
Ex. /search?query=example will have query parameter query and the value is example.
import { useSearchParams } from 'react-router-dom';
const [searchParams] = useSearchParams();
const queryId = searchParams.get('id');
useLocation
useLocation will return information of current URL such as :pathname path of current URLsearch query parameters in current URL ex. "?id=123&name=John".hash hash fragment in URLe ex."#section-2".state state datanavigate from another page.