Commit ff20021f authored by Dawid Szymanski's avatar Dawid Szymanski

Merge branch '2019-08-12-react-context' into 'master'

2019-08-12: react context

See merge request !13
parents c44cb7f2 7f3145cf
# React Contexts
by Przemek Ciąćka
[ClickUp task](https://app.clickup.com/t/1dt6rq)
## Context
### What is Context?
> _Context provides a way to pass data through the component tree without having to pass props down manually at every level._ <sup>[[reactjs.org](https://reactjs.org/docs/context.html)]</sup>
### When to use it?
Context may be used to solve problems with sharing data accross all components in the components tree, like:
- theme colors and settings,
- global configuration,
- i18n texts and configuration,
- anything that fit into the scope of contexts.
#### Example
For example in the code below props with content texts are passed manually:
```JavaScript
const App = ({ children }) => {
const i18n = {
appName: 'Front-end weekly application',
profile: {
settings: 'Profile settings',
logout: 'Logout'
}
};
return (
<>
<Sidebar i18n={i18n} />
<Content>
<ToolBar i18n={i18n} />
{children}
</Content>
</>
);
}
const Sidebar = ({ i18n }) => {
return (
<div class="sidebar">
<header>{i18n.appName}</header>
<ul>
<li>Link 1</li>
<li>Link 2</li>
</ul>
</div>
);
};
const Toolbar = ({ i18n }) => {
return (
<div class="toolbar">
<h1>{i18n.appName}</h1>
<div class="toolbar__profileDropdown">
<div class="item">{i18n.profile.settings}</div>
<div class="item">{i18n.profile.logout}</div>
</div>
</div>
);
};
```
Instead of passing `i18n` object to every component manually we can use context
to define, store and distibute `i18n` object to all components in the tree
automatically, like this:
```JavaScript
const i18n = {
appName: 'Front-end weekly application',
profile: {
settings: 'Profile settings',
logout: 'Logout'
}
};
const I18NContext = React.createContext(i18n);
// I18NContext provider is responsible for passing context's value to all
// components in the tree, automatically.
const App = ({ children }) => {
return (
<I18NContext.Provider value={i18n}>
<Sidebar />
<Content>
<ToolBar />
{children}
</Content>
</>
);
}
const Sidebar = () => {
const i18n = useContext(I18NContext);
return (
<div class="sidebar">
<header>{i18n.appName}</header>
<ul>
<li>Link 1</li>
<li>Link 2</li>
</ul>
</div>
);
};
const Toolbar = () => {
const i18n = useContext(I18NContext);
return (
<div class="toolbar">
<h1>{i18n.appName}</h1>
<div class="toolbar__profileDropdown">
<div class="item">{i18n.profile.settings}</div>
<div class="item">{i18n.profile.logout}</div>
</div>
</div>
);
};
```
### Dynamic context updates
Besides storing static value context may be constructed in a way that allows its
dynamic update. More about that you can find at [https://reactjs.org/docs/context.html#dynamic-context](https://reactjs.org/docs/context.html#dynamic-context)
## Example App
In directory [2019-08-12-react-context](./2019-08-12-react-context) you can find an example implementation of React Context.
This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app).
## Available Scripts
In the project directory, you can run:
### `npm start`
Runs the app in the development mode.<br>
Open [http://localhost:3000](http://localhost:3000) to view it in the browser.
The page will reload if you make edits.<br>
You will also see any lint errors in the console.
### `npm test`
Launches the test runner in the interactive watch mode.<br>
See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information.
### `npm run build`
Builds the app for production to the `build` folder.<br>
It correctly bundles React in production mode and optimizes the build for the best performance.
The build is minified and the filenames include the hashes.<br>
Your app is ready to be deployed!
See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information.
### `npm run eject`
**Note: this is a one-way operation. Once you `eject`, you can’t go back!**
If you aren’t satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project.
Instead, it will copy all the configuration files and the transitive dependencies (Webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point you’re on your own.
You don’t have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldn’t feel obligated to use this feature. However we understand that this tool wouldn’t be useful if you couldn’t customize it when you are ready for it.
## Learn More
You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started).
To learn React, check out the [React documentation](https://reactjs.org/).
This diff is collapsed.
{
"name": "react-context",
"version": "0.1.0",
"private": true,
"dependencies": {
"@material-ui/core": "^4.3.2",
"@material-ui/icons": "^4.2.1",
"@types/jest": "24.0.17",
"@types/node": "12.7.1",
"@types/react": "16.9.1",
"@types/react-dom": "16.8.5",
"@types/styled-components": "^4.1.18",
"react": "^16.9.0",
"react-dom": "^16.9.0",
"react-scripts": "3.1.0",
"styled-components": "^4.3.2",
"typescript": "3.5.3"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": "react-app"
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta
name="description"
content="Web site created using create-react-app"
/>
<title>React App</title>
</head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
</body>
</html>
.App {
text-align: center;
}
.App-logo {
animation: App-logo-spin infinite 20s linear;
height: 40vmin;
pointer-events: none;
}
.App-header {
background-color: #282c34;
min-height: 100vh;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
font-size: calc(10px + 2vmin);
color: white;
}
.App-link {
color: #61dafb;
}
@keyframes App-logo-spin {
from {
transform: rotate(0deg);
}
to {
transform: rotate(360deg);
}
}
import React from "react";
import "./App.css";
import AppLayout from "./components/AppLayout";
import Content from "./components/Content";
import { ThemeContext, theme } from "./contexts/ThemeContext";
import { SnackbarContextProvider } from "./contexts/SnackbarContext";
const App: React.FC = () => {
return (
<ThemeContext.Provider value={theme}>
<SnackbarContextProvider>
<AppLayout>
<Content />
</AppLayout>
</SnackbarContextProvider>
</ThemeContext.Provider>
);
};
export default App;
import React, { useContext } from "react";
import styled from "styled-components";
import TheSidebar from "./TheSidebar";
import { ThemeContext } from "../contexts/ThemeContext";
const StyledWrapper = styled.div`
display: flex;
width: 100%;
height: 100%;
`;
const StyledContentWrapper = styled.div`
padding: 20px;
flex: 1;
`;
const AppLayout: React.FC = ({ children }) => {
const theme = useContext(ThemeContext);
const backgroundColor = theme.content;
return (
<StyledWrapper>
<TheSidebar />
<StyledContentWrapper style={{ backgroundColor }}>
{children}
</StyledContentWrapper>
</StyledWrapper>
);
};
export default AppLayout;
import React, { useContext } from "react";
import { SnackbarContext } from "../contexts/SnackbarContext";
const Content = () => {
const snackbar = useContext(SnackbarContext);
return (
<div>
<button onClick={snackbar.openSnackbar}>Show snackbar</button>
</div>
);
};
export default Content;
import React, { useContext } from "react";
import MaterialSnackbar from "@material-ui/core/Snackbar";
import IconButton from "@material-ui/core/IconButton";
import Close from "@material-ui/icons/Close";
import { SnackbarContext } from "../contexts/SnackbarContext";
interface SnackbarProps {
open: boolean;
}
const Snackbar = ({ open }: SnackbarProps) => {
const snackbarContext = useContext(SnackbarContext);
return (
<MaterialSnackbar
anchorOrigin={{ vertical: "bottom", horizontal: "left" }}
open={open}
autoHideDuration={6000}
ClickAwayListenerProps={{ onClickAway: () => null }}
onClose={snackbarContext.closeSnackbar}
message="This is my snackbar"
action={[
<IconButton
key="close"
color="inherit"
onClick={snackbarContext.closeSnackbar}
>
<Close />
</IconButton>
]}
/>
);
};
export default Snackbar;
import React, { useContext } from "react";
import styled from "styled-components";
import { ThemeContext } from "../contexts/ThemeContext";
const StyledSidebarWrapper = styled.div<{ backgroundColor: string }>`
background-color: ${p => p.backgroundColor};
height: 100%;
width: 300px;
padding: 20px;
box-sizing: border-box;
display: flex;
flex-direction: column;
`;
const TheSidebar = () => {
const theme = useContext(ThemeContext);
const siedbarBackground = theme.sidebar;
return (
<StyledSidebarWrapper backgroundColor={siedbarBackground}>
Sidebar Content
</StyledSidebarWrapper>
);
};
export default TheSidebar;
import React, { useState, useMemo } from "react";
import Snackbar from "../components/Snackbar";
export const SnackbarContext = React.createContext({
openSnackbar: () => {},
closeSnackbar: () => {}
});
export const SnackbarContextProvider: React.FC = ({ children }) => {
const [open, setOpen] = useState(false);
const ctxValue = useMemo(() => {
const openSnackbar = () => setOpen(true);
const closeSnackbar = () => setOpen(false);
return { openSnackbar, closeSnackbar };
}, []);
return (
<SnackbarContext.Provider value={ctxValue}>
<Snackbar open={open} />
{children}
</SnackbarContext.Provider>
);
};
import React from "react";
export const theme = {
sidebar: "#efefef",
content: "#ffffff"
};
export const ThemeContext = React.createContext({
...theme
});
html,
body,
#root {
height: 100%;
}
body {
margin: 0;
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "Roboto", "Oxygen",
"Ubuntu", "Cantarell", "Fira Sans", "Droid Sans", "Helvetica Neue",
sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
code {
font-family: source-code-pro, Menlo, Monaco, Consolas, "Courier New",
monospace;
}
import React from "react";
import ReactDOM from "react-dom";
import "./index.css";
import App from "./App";
ReactDOM.render(<App />, document.getElementById("root"));
{
"compilerOptions": {
"target": "es5",
"lib": [
"dom",
"dom.iterable",
"esnext"
],
"allowJs": true,
"skipLibCheck": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"jsx": "react"
},
"include": [
"src"
]
}
This diff is collapsed.
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment