-
-
- Node >= 8.10
- NPM >= 5.6
-
- npx create-react-app my-app
- cd my-app
- npm start
-
import ReactDOM from "react-dom"; import React from "react"; const element = <h2>Hello developers team :) </h2> ReactDOM.render( element, document.getElementById('root') );
-
-
import './style.css
-
.btn{ background-color: #0000ff; color: #ffffff; }
-
- npm install bootstrap
import 'bootstrap/dist/css/bootstrap.css';
-
-
-
class Welcome extends React.Component { render() { return <h1>Hello, {this.props.nackName}</h1>; } }
-
function Welcome(props) { return <h1>{props.nackName}</h1> }
-
-
-
- componentDidMount
- componentWillUnmount
-
- componentDidUpdate
- shouldComponentUpdate
- render
- getSnapshotBeforeUpdate
-
class MyImage extends Component { constructor(props) { super(props); console.log('inital component'); } componentDidMount(){ console.log('did mount'); } componentWillUnmount(){ console.log('component destroy'); } render() { return ( <div> <img src="https://www.elegantthemes.com/blog/wp-content/uploads/2018/04/Best-Code-and-Text-Editors.png"/> </div> ); } } class ImplementLifeCycle extends Component { constructor(props) { super(props); this.state = { isShow: false } } showImage = ()=>{ this.setState({isShow: !this.state.isShow}); } render() { return ( <div > <button onClick={this.showImage}>show an image</button> {this.state.isShow ? <MyImage /> : null} </div> ); } }
ReactDOM.render( <ImplementLifeCycle />, document.getElementById('root') );
-
- using Hooks
-
-
-
constructor(props) { super(props); this.state = {title: props.title}; this.handleClick = this.handleClick.bind(this); } handleClick() { console.log("clicked me..", this.state); }
=========== or use arraw function like so ===========
handleClick = ()=>{ console.log("clicked me..", this.state); }
render() { return ( <div> <button onClick={this.handleClick} >Click Me</button> </div> ); }
-
function Welcome() { function handleClick(e) { e.preventDefault(); console.log('The link was clicked.'); } return ( <a href="#" onClick={handleClick}> Click me </a> ); }
-
-
class NameForm extends React.Component { constructor(props) { super(props); this.state = {value: ''}; this.handleChange = this.handleChange.bind(this); this.handleSubmit = this.handleSubmit.bind(this); } handleChange(event) { this.setState({value: event.target.value}); } handleSubmit(event) { alert('A name was submitted: ' + this.state.value); event.preventDefault(); }
render() { return ( <form onSubmit={this.handleSubmit}> <label> Name: <input type="text" value={this.state.value} onChange={this.handleChange} /> </label> <input type="submit" value="Submit" /> </form> ); } }
- Exercies : convert newform component class to the functional component class
-
-
import React, {createContext, Component} from 'react'; export const SongsContext = createContext(); class SongsContextProvider extends Component { state = { songs: [ {id:12, name: 'Ali'}, {id:13, name: 'Kali'}, {id:14, name: 'Omer'}, ] } addSong =()=>{ var joined = this.state.songs.concat({id:122, name: 'Ommm'}); this.setState({ songs: joined }) } render() { return ( <SongsContext.Provider value={{songs:this.state.songs, addSong: this.addSong}}> {this.props.children} </SongsContext.Provider> ); } } export default SongsContextProvider;
class ImplementHook extends Component { static contextType = SongsContext; render() { const {songs, addSong} = this.context; return ( <div> <ul> {songs.map(song => { return ( <li key={song.id}>{song.name}</li> ); })} </ul> <button onClick={addSong}>add newSong</button> </div> ); } }
ReactDOM.render( <SongsContextProvider> <ImplementHook /> </SongsContextProvider>, document.getElementById('root') );
-
class MyComponent extends Component { render() { return ( <FoodContext.Consumer>{(foodContext) => ( <SongContext.Consumer>{(songsContext)=> { const { isFood, changeStatus } = foodContext; const { songs } = songsContext; return ( <div> <h1>Hello developers </h1> <h3>Food : {isFood ? 'true' : 'false'}</h3> <button onClick={changeStatus}>change status</button> <ul> {songs.map(song => { return ( <li key={song.id}>{song.name}</li> ) })} </ul> </div> ) }}</SongContext.Consumer> )}</FoodContext.Consumer> ); } }
-
const MyComponent = () => { const {songs} = useContext(SongContext); const {changeStatus, isFood} = useContext(FoodContext); return ( <div> <h1>Hello developers </h1> <h3>Food : {isFood ? 'true' : 'false'}</h3> <button onClick={changeStatus}>change status</button> <ul> {songs.map(song => { return ( <li key={song.id}>{song.name}</li> ) })} </ul> </div> ); }
-
-
-
The most important thing in the hooks is these three methods :
- useState
- useEffect
- useContext
-
Implement Hooks functions like so:
const ImplementHook = () => { const [songs, setSongs] = useState([ {id:1, name: 'Otwel'}, {id:2, name: 'Omda'}, {id:3, name: 'Jhon'}, ]); const [age, setAge] = useState(10); useEffect(()=>{ console.log('effect hooks', songs); }, [songs]); useEffect(()=>{ console.log('effect hooks', age); }, [age]); const handlClick =()=>{ setSongs([...songs, {id:4, name:'new song'}]); } return ( <div> <ul> {songs.map(song => { return ( <li key={song.id}>{song.name}</li> ); })} </ul> <button onClick={handlClick}>add newSong</button> <button onClick={() => {document.title = setAge(age+1)}}>add age</button> </div> ); }
ReactDOM.render( <ImplementHook />, document.getElementById('root') );
-
-
import React, {useContext} from 'react'; const ImplementHook = () => { const {songs, addSong} = useContext(SongsContext); return ( <div> <ul> {songs.map(song => { return ( <li key={song.id}>{song.name}</li> ); })} </ul> <button onClick={addSong}>add newSong</button> </div> ); }
-
import useFriendStatus from "./customeHooks/friends"; const App = () => { const songs = useFriendStatus(); return ( <div> <ul> {songs.map(song => { return ( <li>{song.name}</li> ) })} </ul> </div> ); } function useFriendStatus() { const [songs, setSongs] = useState([ { id:10, name: 'Owel City' }, { id:11, name: 'Owel City2' } ]); useEffect(()=>{ console.log('effect hooks'); }, []); return songs; } export default useFriendStatus;
-
-
- BrowserRouter
- Link
- Route
- NavLink
-
import { BrowserRouter as Router, Switch, Route, Link } from "react-router-dom"; const NavBar = () => { return ( <div> <ul> <li><Link to="/home">Home</Link></li> <li><Link to="/about" >About us </Link></li> </ul> <Switch> <Route path="/home" component={Home}></Route> <Route path="/aboutd" component={About}></Route> </Switch> </div> ); }
-
const Home = (props) => { return <h2>Home page `your ID is ${props.match.params.id}`</h2>; } const NavBar = () => { return ( <div> <ul> <li><Link to="/home/200">Home</Link></li> <li><Link to="/about" >About us </Link></li> </ul> <Switch> <Route path="/home/:id" component={Home}></Route> <Route path="/aboutd" component={About}></Route> </Switch> </div> ); }
-
-
-
. |-src |- components | |-component-name-folder | |-component-name.js | |-component-name.sass | |-component-name.styles.js | |-component-name-test.js | |-index.js |-routes |-index.js |-index.js
-
-
-
const reducer = function(state={counter:0}, action){ switch (action.type) { case "INC":{ return state + action.payload; } } return state; } const store = createStore(reducer, {counter:0}); store.subscribe(()=>{ console.log("Store channged", store.getState()); }); store.dispatch({type:"INC", payload: 20}); store.dispatch({type:"INC", payload: 200});
-
import {combineReducers, createStore} from 'redux'; const userReducer = function(state = initalData, action){ switch (action.type) { case "CHANGE_NAME": state.name = action.payload; break; case "CHANGE_EMAIL": state.email = action.payload; break; } return state; }; const taskgReducer = function(state = {}, action){ return state; }; const reducers = combineReducers({ user: userReducer, task: taskgReducer, }); const store = createStore(reducers);
-
-
import {applyMiddleware} from 'redux'; const logger = (store)=>(next) => (action) => { next(action); }; const middleware = applyMiddleware(logger); const store = createStore(reducers, {}, middleware);
-
- Logger (
"redux-logger"
) - Thunk (
"redux-thunk"
)store.dispatch((dispatch)=>{ Axios.get('https://jsonplaceholder.typicode.com/todos') .then(response => { dispatch({type:'FETCH_TASKS', payload:response.data}); console.log(response.data); }) .catch(error=>{ dispatch({type:'ERROR', payload:error}); }) });
- Promise (
"redux-promise-middleware"
)
- Logger (
-
-
- Use example of the middleware
Thunk
- Use Promise middelware
store.dispatch({ type: "FETCH_TASKS", payload: Axios.get('https://jsonplaceholder.typicode.com/todos') });
- Use example of the middleware
-
-
|-src |-components |-actions |-userActoins.js |-postActions.js |-reducers |-userReducer.js |-postReducer.js |-index.js |-store.js
-
import {applayMiddleware, createStore } from 'redux'; import reducers from './reducers'; import promise from 'redux-promise-middleware'; import thunk from 'redux-thunk'; import logger from 'redux-logger'; const middlewares = applayMiddleware(promise, thunk, logger); export default createStore(reducers, middlewares);
-
import {compineReducers} from 'redux'; import taskReducer from './taskReducer'; export default compineReducers({ taskReducer });
-
export default function reducer(state = {tasks: [], error: null}, action){ switch (action.type) { case "FETCH_TASKS_PENDDING":{ return {...state, tasks: action.payload}; } case "FETCH_TASKS_FULFILLED":{ return {...state, tasks: action.payload.data}; } case "ADD_TASK":{ return {...state, tasks: state.tasks.concat(action.payload)}; } case "GET_TASK":{ return {...state, tasks: state.tasks.find(action.payload.id)}; } case "FETCH_TASKS_REJECTED": return {...state, error: action.payload}; } return state; };
-
import Axios from "axios" export function fetchTasks(){ return function(dispatch) => { Axios.get() .then(response =>{ dispatch({type:'FETCH_TASKS_FULFILLED', payload:reponse.data}); }) .catch(error =>{ dispatch({type:'FETCH_TASKS_REJECTED', payload:error}); }); } } export function addTask(id, name, complete){ return { type:'ADD_TASK', payload:{ id, name, complete } } }
-
-
- Use connect with mapStatToProps
const mapStateToProps = state =>{ return { task: state.task, user: state.user } }; class App extends React.Component { render() { console.log(this.props); return ( <div className="container"> Hello, Omda </div> ); } } export default connect(mapStateToProps, (App);
- Use connect with mapDispatchToProps
class App extends React.Component { render() { console.log(this.props.dispatch(fetchTasks())); return ( <div className="container"> Hello, Omda </div> ); } }
- Use connect with mapStatToProps
-
-
-
- by using React Hook I thing there is no need for a statage mangement ?!
- Componenet functional base it's better than componenet class base ?
- Your thought reactjs vs vuejs
- Redux vs Vuex
-
- What is .tsx
- Reducers with Hooks