React ~ Router ~ Primary Components - rohit120582sharma/Documentation GitHub Wiki

Routers

Allows React Router to pass the app's routing information down to any child component it needs (via context).

The react-router-dom provides <BrowserRouter> and <HashRouter> routers. The main difference between the two is the way they store the URL and communicate with your web server.

<BrowserRouter>

It uses regular URL paths. These are generally the best-looking URLs, but they require your server to be configured correctly. Specifically, your web server needs to serve the same page at all URLs that are managed client-side by React Router.

It uses the HTML5 History API to keep track of routes history and to keep your UI in sync with the URL.

<HashRouter>

It stores the current location in the hash portion of the URL, so the URL looks something like http://example.com/#/your/page. Since the hash is never sent to the server, this means that no special server configuration is needed.

import { BrowserRouter as Router } from 'react-router-dom';

ReactDOM.render((
    <Router>
        <App/>
    </Router>
), document.getElementById('root'));


Route Matching

There are two route matching components: <Route> and <Switch>.

<Route>

This component is the most important component in React router. It renders some UI if the current location matches the Route’s props named path, when it doesn't, it will render null.

The path is used to identify the portion of the URL that the router should match. It uses the Path-to-RegExp library to turn a path string into a regular expression. It will then be matched against the current location.

It has three props that you can you use to define what gets rendered: component, render, and children.

<Switch>

When multiple Route are used together, all the routes that match are rendered inclusively.

The Switch component is used to group Route together. With <Switch>, only the first child <Route> that matches the location gets rendered.



Navigation

There are three navigation components: <Link>, <NavLink>, and <Redirect>

<Link>

This component creates a link in the application. Wherever you render a Link, an anchor (<a>) will be rendered in your application’s HTML. However, using anchor links would result in a browser refresh, which we don’t want. So instead, we can use Link to navigate to a particular URL and have the view re-rendered without a browser refresh.

<NavLink>

It is a special type of Link that can style itself as “active” when its to prop matches the current location.

<Redirect>

Rendering a Redirect will navigate to a new location. The new location will override the current location in the history stack, like server-side redirects (HTTP 3xx) do.

⚠️ **GitHub.com Fallback** ⚠️