DOM vs. Virtual DOM

Routing

import React from 'react';
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';

import Nav from '../common/nav/Nav'
import PageNotFound from '../common/pageNotFound/PageNotFound';
import HomePage from '../homePage/HomePage';
import ContactList from '../contactList/ContactList';

function App() {
  return (
    <Router>
      <div className="container-fluid mt-3">
        <Nav></Nav>
        <Switch>
          <Route exact path="/" component={HomePage} />
          <Route exact path="/contacts" component={ContactList} />
          <Route path='contacts/:id' component={ContactItem} />
          <Route component={PageNotFound} />
        </Switch>
      </div>
    </Router>
  );
}

export default App;

Custom Config

<Route path='/'>
  <DefaultRoute handler={Home} />
  <NotFoundRoute handler={NotFound} />
  
  <Redirect from='login' to='sessions/new' />
  <Redirect from='login' to='sessions/new' params={{from: 'home'}} />
  <Redirect from='profile/:id' to='about-user' />

<Route name='about-user' ... />

NavLink

import React from 'react';
import { NavLink } from 'react-router-dom';

function Nav() {
    const activeStyle = { color: 'navy' };
    return (
        <nav className="mb-3">
            <NavLink to="/" exact activeStyle={activeStyle}>Home</NavLink>
            {"  |  "}
            <NavLink to="/contacts" activeStyle={activeStyle}>Contacts</NavLink>
        </nav>
    )
}

export default Nav;

Get Route Params

let MyComponent() {
    // From the path `/inbox/messages/:id`
    const id = this.props.params.id
}

const mapStateToProps = (state, ownProps) => ({
		movieId: ownProps.match.params.movieId
});

Link

import { Link } from 'react-router'

<Link to={`/users/${user.id}`}>{user.username}</Link>
<Link to='login' activeClassName='-active' onClick='...'>

Navigation

import { useNavigate} from "react-router-dom";

const MyComponent = () => {
    const navigate = useNavigate();

    const onFormCanceled = () => {
        navigate('/users');
    }
}

useParams

import * as React from 'react';
import { Routes, Route, useParams } from 'react-router-dom';

function ProfilePage() {
  // Get the userId param from the URL.
  let { userId } = useParams();
  // ...
}

function App() {
  return (
    <Routes>
      <Route path="users">
        <Route path=":userId" element={<ProfilePage />} />
        <Route path="me" element={...} />
      </Route>
    </Routes>
  );
}

useLocation