Skip to content

Instantly share code, notes, and snippets.

@mklishevych
Created January 17, 2019 21:16
Show Gist options
  • Save mklishevych/49da77739a324c415567b5392b034c32 to your computer and use it in GitHub Desktop.
Save mklishevych/49da77739a324c415567b5392b034c32 to your computer and use it in GitHub Desktop.
.app {
display: flex;
flex-direction: column;
}
.header {
display: flex;
align-items: center;
justify-content: center;
min-width: 100vw;
height: 96px;
font-size: calc(10px + 2vmin);
color: white;
}
.header p {
margin-right: 24px;
}
.header.light {
background-color: #ffba00;
}
.header.dark {
background-color: #282c34;
}
.contentContainer {
display: flex;
flex-direction: column;
position: absolute;
width: 100vw;
top: 96px;
height: calc(100vh - 96px);
align-items: center;
justify-content: center;
}
.contentContainer.light {
background-color: white;
}
.contentContainer.dark {
background-color: #30353d;
}
p.light {
color: black;
}
p.dark {
color: white;
}
import React, { useState } from 'react';
import './App.css';
import Content from './components/content';
import { ThemeContext } from './shared/context';
function App() {
const [theme, setTheme] = useState('dark');
return (
<ThemeContext.Provider value={theme}>
<div className="app">
<header className={`header ${theme}`}>
<p>Testing NEW 1...2...3...</p>
<button onClick={() => setTheme('light')}>Light</button>
<button onClick={() => setTheme('dark')}>Dark</button>
</header>
<div className={`contentContainer ${theme}`}>
<p className={theme}>Our gorgeous content</p>
<Content />
</div>
</div>
</ThemeContext.Provider>
);
}
export default App;
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
it('renders without crashing', () => {
const div = document.createElement('div');
ReactDOM.render(<App />, div);
ReactDOM.unmountComponentAtNode(div);
});
import React, { Component } from 'react';
import './App.css';
import ContentOld from './components/contentOld';
class AppOld extends Component {
constructor(props) {
super(props);
this.state = {
theme: 'dark'
}
}
setTheme = (theme) => {
this.setState({ theme });
};
render () {
const { theme } = this.state;
return (
<div className="app">
<header className={`header ${theme}`}>
<p>Testing OLD 1...2...3...</p>
<button onClick={() => this.setTheme('light')}>Light</button>
<button onClick={() => this.setTheme('dark')}>Dark</button>
</header>
<div className={`contentContainer ${theme}`}>
<p className={theme}>Our gorgeous content</p>
<ContentOld theme={theme} />
</div>
</div>
);
}
}
export default AppOld;
.content {
display: flex;
flex-direction: column;
}
.contentInput {
display: flex;
height: 32px;
width: 240px;
border-color: red;
border-radius: 4px;
margin-bottom: 24px;
}
p {
text-align: center;
}
p.light {
color: black;
}
p.dark {
color: white;
}
import React, { useState, useContext, useEffect } from 'react';
import './content.css';
import { ThemeContext } from '../shared/context';
// Custom hook demo
// import { useWindowWidth, useFormInput } from '../shared/customHooks';
function Content() {
const theme = useContext(ThemeContext);
const [ text, setText ] = useState(theme);
// Side effects demo
const [ width, setWidth ] = useState(window.innerWidth);
useEffect(() => {
document.title = text;
});
useEffect(() => {
window.addEventListener('resize', handleResize);
return () => {
window.removeEventListener('resize', handleResize);
};
});
function handleResize() {
setWidth(window.innerWidth);
}
return (
<div className='content'>
<input
className='contentInput'
defaultValue={theme}
onChange={(e) => setText(e.target.value)}
/>
<p className={theme}>{width}px</p>
</div>
);
}
export default Content;
import React, { Component } from 'react';
import './content.css';
class ContentOld extends Component {
constructor (props) {
super(props);
this.state = {
val: 'dark',
width: window.innerWidth
};
this.setText = this.setText.bind(this);
this.handleResize = this.handleResize.bind(this);
}
componentDidMount() {
document.title = this.state.val;
window.addEventListener('resize', this.handleResize)
}
componentDidUpdate() {
document.title = this.state.val;
}
componentWillUnmount() {
window.removeEventListener('resize', this.handleResize)
}
setText(event) {
this.setState({ val: event.target.value });
}
handleResize() {
this.setState({
width: window.innerWidth
});
}
render () {
return (
<div className='content'>
<input
className='contentInput'
defaultValue={this.props.theme}
onChange={this.setText}
/>
<p className={this.props.theme}>{this.state.width}px</p>
</div>
);
}
}
export default ContentOld;
body {
margin: 0;
padding: 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';
import AppOld from './AppOld';
import * as serviceWorker from './serviceWorker';
ReactDOM.render(<App />, document.getElementById('root'));
// ReactDOM.render(<AppOld />, document.getElementById('root'));
// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.
// Learn more about service workers: http://bit.ly/CRA-PWA
serviceWorker.unregister();
// This optional code is used to register a service worker.
// register() is not called by default.
// This lets the app load faster on subsequent visits in production, and gives
// it offline capabilities. However, it also means that developers (and users)
// will only see deployed updates on subsequent visits to a page, after all the
// existing tabs open on the page have been closed, since previously cached
// resources are updated in the background.
// To learn more about the benefits of this model and instructions on how to
// opt-in, read http://bit.ly/CRA-PWA
const isLocalhost = Boolean(
window.location.hostname === 'localhost' ||
// [::1] is the IPv6 localhost address.
window.location.hostname === '[::1]' ||
// 127.0.0.1/8 is considered localhost for IPv4.
window.location.hostname.match(
/^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/
)
);
export function register(config) {
if (process.env.NODE_ENV === 'production' && 'serviceWorker' in navigator) {
// The URL constructor is available in all browsers that support SW.
const publicUrl = new URL(process.env.PUBLIC_URL, window.location.href);
if (publicUrl.origin !== window.location.origin) {
// Our service worker won't work if PUBLIC_URL is on a different origin
// from what our page is served on. This might happen if a CDN is used to
// serve assets; see https://github.com/facebook/create-react-app/issues/2374
return;
}
window.addEventListener('load', () => {
const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`;
if (isLocalhost) {
// This is running on localhost. Let's check if a service worker still exists or not.
checkValidServiceWorker(swUrl, config);
// Add some additional logging to localhost, pointing developers to the
// service worker/PWA documentation.
navigator.serviceWorker.ready.then(() => {
console.log(
'This web app is being served cache-first by a service ' +
'worker. To learn more, visit http://bit.ly/CRA-PWA'
);
});
} else {
// Is not localhost. Just register service worker
registerValidSW(swUrl, config);
}
});
}
}
function registerValidSW(swUrl, config) {
navigator.serviceWorker
.register(swUrl)
.then(registration => {
registration.onupdatefound = () => {
const installingWorker = registration.installing;
if (installingWorker == null) {
return;
}
installingWorker.onstatechange = () => {
if (installingWorker.state === 'installed') {
if (navigator.serviceWorker.controller) {
// At this point, the updated precached content has been fetched,
// but the previous service worker will still serve the older
// content until all client tabs are closed.
console.log(
'New content is available and will be used when all ' +
'tabs for this page are closed. See http://bit.ly/CRA-PWA.'
);
// Execute callback
if (config && config.onUpdate) {
config.onUpdate(registration);
}
} else {
// At this point, everything has been precached.
// It's the perfect time to display a
// "Content is cached for offline use." message.
console.log('Content is cached for offline use.');
// Execute callback
if (config && config.onSuccess) {
config.onSuccess(registration);
}
}
}
};
};
})
.catch(error => {
console.error('Error during service worker registration:', error);
});
}
function checkValidServiceWorker(swUrl, config) {
// Check if the service worker can be found. If it can't reload the page.
fetch(swUrl)
.then(response => {
// Ensure service worker exists, and that we really are getting a JS file.
const contentType = response.headers.get('content-type');
if (
response.status === 404 ||
(contentType != null && contentType.indexOf('javascript') === -1)
) {
// No service worker found. Probably a different app. Reload the page.
navigator.serviceWorker.ready.then(registration => {
registration.unregister().then(() => {
window.location.reload();
});
});
} else {
// Service worker found. Proceed as normal.
registerValidSW(swUrl, config);
}
})
.catch(() => {
console.log(
'No internet connection found. App is running in offline mode.'
);
});
}
export function unregister() {
if ('serviceWorker' in navigator) {
navigator.serviceWorker.ready.then(registration => {
registration.unregister();
});
}
}
import React from 'react';
export const ThemeContext = React.createContext('dark');
import { useEffect, useState } from 'react';
export function useWindowWidth() {
const [width, setWidth] = useState(window.innerWidth);
useEffect(() => {
window.addEventListener('resize', handleResize);
return () => {
window.removeEventListener('resize', handleResize);
};
});
function handleResize() {
setWidth(window.innerWidth);
}
return width;
}
export function useFormInput(initValue) {
const [value, setValue] = useState(initValue);
function handleChange(event) {
setValue(event.target.value);
}
return {
value,
onChange: handleChange
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment