Browse Source

tutorial

master
cupcakearmy 1 year ago
parent
commit
096d33baa8
15 changed files with 364 additions and 89 deletions
  1. + 2
    - 76
      .gitignore
  2. + 11
    - 11
      LICENSE
  3. + 40
    - 2
      README.md
  4. + 29
    - 0
      package.json
  5. + 32
    - 0
      src/Hooks.js
  6. + 37
    - 0
      src/Screens/App.jsx
  7. + 14
    - 0
      src/Screens/Custom.jsx
  8. + 18
    - 0
      src/Screens/Posts.jsx
  9. + 36
    - 0
      src/Screens/Ref.jsx
  10. + 53
    - 0
      src/Screens/Simple.jsx
  11. + 8
    - 0
      src/Styles/global.styl
  12. + 14
    - 0
      src/index.html
  13. + 7
    - 0
      src/index.jsx
  14. + 1
    - 0
      src/index.styl
  15. + 62
    - 0
      webpack.config.js

+ 2
- 76
.gitignore

@ -1,78 +1,4 @@
# ---> Node
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
# Runtime data
pids
*.pid
*.seed
*.pid.lock
# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov
# Coverage directory used by tools like istanbul
coverage
# nyc test coverage
.nyc_output
# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files)
.grunt
# Bower dependency directory (https://bower.io/)
bower_components
# node-waf configuration
.lock-wscript
# Compiled binary addons (https://nodejs.org/api/addons.html)
build/Release
# Dependency directories
node_modules/
jspm_packages/
# TypeScript v1 declaration files
typings/
# Optional npm cache directory
.npm
# Optional eslint cache
.eslintcache
# Optional REPL history
.node_repl_history
# Output of 'npm pack'
*.tgz
# Yarn Integrity file
.yarn-integrity
# dotenv environment variables file
.env
# parcel-bundler cache (https://parceljs.org/)
.cache
# next.js build output
.next
# nuxt.js build output
.nuxt
# vuepress build output
.vuepress/dist
# Serverless directories
.serverless
# FuseBox cache
.fusebox/
package-lock.json
.idea

+ 11
- 11
LICENSE

@ -1,21 +1,21 @@
MIT License
Copyright (c) <year> <copyright holders>
Copyright (c) 2018 Nicco
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is furnished
to do so, subject to the following conditions:
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice (including the next
paragraph) shall be included in all copies or substantial portions of the
Software.
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS
OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF
OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

+ 40
- 2
README.md

@ -1,3 +1,41 @@
# guide-react-hooks
# Minimal React Boilerplate 👨‍🍳
Practical guide to react hooks
This is the starting point for any react project to get up and running quickly.
Uses:
- React 16.8 (with hooks)
- Babel 7
- Webpack 4
- Stylus
## Getting Started 🚀
```bash
git clone https://github.com/CupCakeArmy/react-boilerplate.git
npm i
npm run dev
# Or
wget https://github.com/CupCakeArmy/react-boilerplate/archive/master.zip
unzip master
```
### Build 🛠
```bash
# Dev
npm run build:dev
# Prod
npm run build:prod
```
### Dev 👀
Compiles on files changed
```bash
npm run dev
# Go to
http://localhost:8080
```

+ 29
- 0
package.json

@ -0,0 +1,29 @@
{
"private": true,
"scripts": {
"build:dev": "webpack -d",
"build:prod": "webpack -p",
"dev": "webpack-dev-server -d"
},
"dependencies": {
"react": "^16.8",
"react-dom": "^16.8",
"react-router-dom": "^5.0.0"
},
"devDependencies": {
"@babel/core": "^7",
"@babel/preset-env": "^7",
"@babel/preset-react": "^7",
"babel-loader": "^8",
"css-loader": "^2",
"file-loader": "^3",
"html-loader": "^0",
"html-webpack-plugin": "^3",
"mini-css-extract-plugin": "^0.5",
"stylus": "^0.54",
"stylus-loader": "^3",
"webpack": "^4",
"webpack-cli": "^3",
"webpack-dev-server": "^3.2"
}
}

+ 32
- 0
src/Hooks.js

@ -0,0 +1,32 @@
import { useEffect, useState } from 'react'
export const useWindowSize = () => {
const getCurrentSize = () => ({ height: window.innerHeight, width: window.innerWidth })
const [size, setSize] = useState(getCurrentSize())
useEffect(() => {
const handle = () => setSize(getCurrentSize())
window.addEventListener('resize', handle)
return () => window.removeEventListener('resize', handle)
})
return size
}
export const useCallApi = (url) => {
const [data, setData] = useState()
const update = () => {
fetch(url)
.then(response => response.json())
.then(json => setData(json))
}
useEffect(() => {
update()
}, [])
return [data, update]
}

+ 37
- 0
src/Screens/App.jsx

@ -0,0 +1,37 @@
import React from 'react'
import { BrowserRouter as Router, Link, Route, Switch } from 'react-router-dom'
import Simple from './Simple'
import Ref from './Ref'
import Posts from './Posts'
import Custom from './Custom'
const Routes = [
['Simple', Simple],
['Ref', Ref],
['Custom', Custom],
['Posts', Posts],
]
const App = () => {
return <Router>
<ul>
{Routes.map(([route], i) => <li key={i}>
<Link to={`/${route.toLowerCase()}`}>{route}</Link>
</li>)}
</ul>
<hr/>
<Switch>
{Routes.map(([route, component], i) =>
<Route key={i} path={`/${route.toLowerCase()}`} component={component}/>,
)}
</Switch>
</Router>
}
export default App

+ 14
- 0
src/Screens/Custom.jsx

@ -0,0 +1,14 @@
import React from 'react'
import { useWindowSize } from '../Hooks'
const Custom = ()=> {
const size = useWindowSize()
return <div>
Width: {size.width}
<br/>
Height: {size.height}
</div>
}
export default Custom

+ 18
- 0
src/Screens/Posts.jsx

@ -0,0 +1,18 @@
import React from 'react'
import { useCallApi } from '../Hooks'
const Posts = () => {
const [data] = useCallApi(`https://jsonplaceholder.typicode.com/posts`)
if (!data) return <div>Loading 🕰</div>
return <div>
{data.map((post, i) => <div key={i}>
<h3>{post.title}</h3>
<p>{post.body}</p>
</div>)}
</div>
}
export default Posts

+ 36
- 0
src/Screens/Ref.jsx

@ -0,0 +1,36 @@
import React, { useRef } from 'react'
class RefClass extends React.Component {
constructor(props) {
super(props)
this.myRef = React.createRef()
this.change = this.change.bind(this)
}
change() {
this.myRef.current.style.backgroundColor = '#6ba7ee'
}
render() {
return <div>
<button onClick={this.change}>Change Me</button>
<br/><br/>
<div ref={this.myRef} style={{ width: 50, height: 50, backgroundColor: '#000000' }}/>
</div>
}
}
const RefFN = () => {
const rect = useRef()
const change = () => rect.current.style.backgroundColor = '#6ba7ee'
return <div>
<button onClick={change}>Change Me</button>
<br/><br/>
<div ref={rect} style={{ width: 50, height: 50, backgroundColor: '#000000' }}/>
</div>
}
export default RefFN

+ 53
- 0
src/Screens/Simple.jsx

@ -0,0 +1,53 @@
import React, { useEffect, useState } from 'react'
class SimpleClass extends React.Component {
constructor(props) {
super(props)
this.state = {
counter: 0,
}
}
componentDidMount() {
console.log('Lets goo 🚀')
setTimeout(() => this.setState({ counter: 5 }), 2000)
}
componentDidUpdate() {
console.log(this.state.counter)
}
render() {
return <div>
<div>{this.state.counter}</div>
<br/>
<button onClick={() => this.setState({ counter: this.state.counter - 1 })}>Decrease</button>
<button onClick={() => this.setState({ counter: this.state.counter + 1 })}>Increase</button>
</div>
}
}
const SimpleFC = () => {
const [counter, setCounter] = useState(0)
useEffect(() => {
setTimeout(() => {
setCounter(5)
}, 1000)
}, [])
useEffect(() => {
console.log(counter)
})
return <div>
<div>{counter}</div>
<br/>
<button onClick={() => setCounter(counter - 1)}>Decrease</button>
<button onClick={() => setCounter(counter + 1)}>Increase</button>
</div>
}
export default SimpleFC

+ 8
- 0
src/Styles/global.styl

@ -0,0 +1,8 @@
*
box-sizing border-box
html, body
width 100%
height 100%
margin 0
padding 1em

+ 14
- 0
src/index.html

@ -0,0 +1,14 @@
<!DOCTYPE html>
<html lang="en">
<head>
<title>Basic Setup</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<div id="root"></div>
</body>
</html>

+ 7
- 0
src/index.jsx

@ -0,0 +1,7 @@
import React from 'react'
import ReactDOM from 'react-dom'
import './index.styl'
import App from './Screens/App'
ReactDOM.render(<App/>, document.getElementById('root'))

+ 1
- 0
src/index.styl

@ -0,0 +1 @@
@require 'Styles/*'

+ 62
- 0
webpack.config.js

@ -0,0 +1,62 @@
const path = require('path')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const MiniCssExtractPlugin = require('mini-css-extract-plugin')
module.exports = {
entry: [
'./index.jsx',
],
output: {
filename: '[name].js',
path: path.resolve(__dirname, 'public'),
},
resolve: {
extensions: ['.js', '.jsx'],
},
context: path.resolve(__dirname, 'src'),
devServer: {
contentBase: path.resolve(__dirname, 'public/assets'),
open: true,
historyApiFallback: true,
},
plugins: [
new HtmlWebpackPlugin({
template: 'index.html',
}),
new MiniCssExtractPlugin({
filename: 'bundle.css',
}),
],
module: {
rules: [{
test: /\.jsx?$/,
include: /src/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
presets: ['@babel/preset-react', '@babel/preset-env'],
},
},
}, {
test: /\.html$/,
use: ['html-loader'],
}, {
test: /\.css$/,
use: [MiniCssExtractPlugin.loader, 'css-loader'],
}, {
test: /\.styl$/,
use: [MiniCssExtractPlugin.loader, 'css-loader', 'stylus-loader'],
}, {
test: /\.(ttf|eot|woff|woff2|jpg|png|gif|svg)$/, // Static Files
use: [{
loader: 'file-loader',
options: {
name: '[name].[ext]',
outputPath: './assets/',
},
}],
}],
},
}

Loading…
Cancel
Save