From 6af14dff5a85e21ce5e9aa0af7480fc33fe60df0 Mon Sep 17 00:00:00 2001 From: Marcello Lamonaca Date: Wed, 17 Mar 2021 11:34:22 +0100 Subject: [PATCH] Add React-Router Notes --- JavaScript/React/React Router.md | 103 +++++++++++++++++++++++++++++++ 1 file changed, 103 insertions(+) create mode 100644 JavaScript/React/React Router.md diff --git a/JavaScript/React/React Router.md b/JavaScript/React/React Router.md new file mode 100644 index 0000000..2895428 --- /dev/null +++ b/JavaScript/React/React Router.md @@ -0,0 +1,103 @@ +# React Router + +Popular routing library. Allows to specify a route through React components, declating which component is to be loaded for a given URL. + +Key Components: + +- **Router**: wrap the app entrypoint, usually `BrowserRouter` +- **Route**: "Load this component for this URL" +- **Link**: react-managed anchors that won't post back to the browser + +## Routers + +Router Types: + +- *HashRouter*: `#route`, adds hashes to the URLs +- *BrowserRouter*: `/route`, uses HTML5 history API to provide clean URLs +- *MemoryRouter*: no URL + +```js +// index.js + +//other imports ... + +import { BrowserRouter as Router } from "react-router-dom"; + +React.render( + + + , + document.getElemendById("DomID"); +) +``` + +```js +// Component.js +import { Route, Switch } from "react-router-dom"; + +
+ {/* match route pattern exactly, all subroutes will be matched otherwise */} + + + ... +
+ +// only one child can match, similar to switch-case + + + + {/* mathes all non-existent URLs */} + +``` + +### Redirectin + +```js +import { Redirect } from "react-router-dom"; + +// redirects to another URL, should'nt be rendered on component mount but after an action + + +{ condition && } // redirect if condition is true + +// or redirect manipolating the history (alwais in props) +props.history.push("/new-route"); +``` + +### URL Parameters & Query String + +```js +// Given + +// URL: app.com/route/subroute?param=value + +function Component(props) { + props.match.params.placeholder; // subroute + props.location.query; // { param: value } + props.location.pathname; // /route/subroute?param=value +} +``` + +### Propts + +```js +import { Prompt } from "react-router-dom"; + +// displayes a prompt when the conditioni true + +``` + +## Link + +Clicks on a link created with React-Router will be captured by ract an all the routing will happen client side. + +```js +import { Link } from "react-router-dom"; + +// TARGET: +Text + +// add styling attributes to the rendered element when it matches the current URL. +Text +Text +```