by Elizaveta Anatskaya
— an API for rendering components outside of your app’s DOM hierarchy.
ReactDOM.createPortal(child, container)
Instead of returning an element in a component’s render method, return a portal.
const Outsider = () => ReactDOM.createPortal(<div>I'm outside</div>, document.body)
class App extends Component = {
render() {
return (
<Outsider />
)
}
}
Even though a portal can be anywhere in the DOM tree, it behaves like a normal React child in every other way.
The main difference is that for MPA your server’s response to the browser is the HTML of your page that is ready to be rendered, while for SPA the browser gets a pretty empty document with links to your javascript.
The end-user, who’s accustomed to multi-page apps, expects the following features to be present in an SPA:
— is the process of keeping the browser URL in sync with what’s being rendered on the page.
React Router is a library that lets you handle routing declaratively. The declarative routing approach allows you to control the data flow in your application:
<Route>
<Router>
<Switch>
<Link>
...
React Router is a collection of navigational components.
react-router-dom
/* Import statements */
import React from "react";
import ReactDOM from "react-dom";
/* App is the entry point to the React code.*/
import App from "./App";
/* import BrowserRouter from 'react-router-dom' */
import { BrowserRouter } from "react-router-dom";
ReactDOM.render(
<BrowserRouter>
<App />
</BrowserRouter>,
document.getElementById("root")
);
The <BrowserRouter> uses the HTML5 History API to keep track of the router history.
A router component can only have a single child element
The <Route> component renders some UI if the current location matches the route’s path.
The <Link> component is used to navigate between pages. It’s comparable to the HTML anchor element. However, using anchor links would result in a browser refresh.
Instead we can use <Link> to navigate to a particular URL and have the view re-rendered without a browser refresh.
<Link to="/">Homes</Link>
<Route path="/" component={Home} />
Renders the first child that matches the location.
<Switch>
<Route exact path="/" component={Home} />
<Route path="/category" component={Category} />
<Route path="/products" component={Products} />
</Switch>
<Switch> is unique in that it renders a route exclusively. In contrast, every <Route> that matches the location renders inclusively.
Thanks for your attention!