React Router offers a lot of power and flexibility, we will explore the following features in upcoming slides.
<Route
path="/:a([A-Za-z]+)"
render={({ match, props, location }) => (
<h1>
All word characters: {match.params.a}
{console.log({ match })}
{console.log({ location })}
</h1>
)}
/>
<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>
)}
/>
name=value
pairs afte a ?
in a URL<Link />
Components can pass URL Parameters to a Routeto
param works differently between strings and objectsnew URLSearchParams(params)
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>
);
};
<Route>
instead of allconst 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>
);
};
<Switch>
and <Route>
componentsconst 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>
);
};
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>
);
};
/