React Routing - Going Further

React Router offers a lot of power and flexibility, we will explore the following features in upcoming slides.

React Routing - RegEx Validation

Example

<Route
  path="/:a([A-Za-z]+)"
  render={({ match, props, location }) => (
    <h1>
      All word characters: {match.params.a}
      {console.log({ match })}
      {console.log({ location })}
    </h1>
  )}
/>

React Routing - RegEx Validation Parts

Example

<Route
  path="/:a([A-Za-z]+)/:b(\d+)"
  render={({ match, props, location }) => (
    <h1>
      Words then numbers: {match.params.a} | {match.params.b}
      {console.log({ match })}
      {console.log({ location })}
    </h1>
  )}
/>

CodeSandbox

React Routing - Query Parameters

Example

const Nav = props => {
  return (
    <div>
      <Link to="/path?id=42">Params within 'to'</Link>
      <br />
      <Link to={{ pathname: "/path?id=9000" }}>Params within Pathname</Link>
      <br />
      <Link to={{ pathname: "/path", search: "id=789" }}>
        Params 'Search' property
      </Link>
    </div>
  );
};

CodePen

React Routing - Switch Component

Example

const App = props => {
  return (
    <BrowserRouter>
      <React.Fragment>
        <Nav />
        <Switch>
          <Route path="/posts" component={Posts} />
          <Route path="/authors" component={Authors} />
          <Route path="/:author/:post" component={AuthorPost} />
          <Route exact path="/" component={Home} />
        </Switch>
      </React.Fragment>
    </BrowserRouter>
  );
};

CodeSandbox

React Routing - Catch All Route

Example

const NotFound = () => (
  <div>
    <h1>That page was not found</h1>
  </div>
);

const App = props => {
  return (
    <BrowserRouter>
      <React.Fragment>
        <Nav />
        <Switch>
          <Route path="/posts" component={Posts} />
          <Route path="/authors" component={Authors} />
          <Route exact path="/" component={Home} />
          <Route path="" component={NotFound} />
        </Switch>
      </React.Fragment>
    </BrowserRouter>
  );
};

CodeSandbox

React Routing - Redirection

Examples

const Home = () => <h1>You are Home</h1>;
const Posts = () => <h1>All the Posts</h1>;

const App = props => {
  return (
    <BrowserRouter>
      <React.Fragment>
        <Nav />
          <Route path="/posts" component={Posts} />
          <Route path="/willredirect" render={() => (
            <Redirect to="/posts" />
          )} />
          <Route exact path="/" component={Home} />
      </React.Fragment>
    </BrowserRouter>
  );
};

CodeSandbox

 Previous Lesson

Outline

[menu]

/