<style> // dark mode to not hurt ur eye, remove it to change to default (previous last line from /style) // another dark mode but the code editor dint change dark replace !BJrTq20hE == theme-dark // language list for code block {https://hackmd.io/@Markdown-It/H1ieJ_yiX?type=view} // feature on hackmd {https://hackmd.io/s/features#Blockquote-Tags} {https://hackmd.io/features?both} // spoiler tage on MarkDown {https://meta.stackexchange.com/questions/72877/whats-the-exact-syntax-for-spoiler-markup} {%hackmd BJrTq20hE %} </style> # React CheatSheet v16.3 ## [React](https://reactjs.org/docs/getting-started.html) [**React Blog update**](https://reactjs.org/blog/all.html) [**中文版 React**](https://zh-hant.reactjs.org/docs/getting-started.html) - object value default will be px - middle of JSX use {} to go to jsx immediately,if object double curly{{}} - className replace class property on html - for in html use htmlFor - most css in JS object require Case to replace -, String for value - JS object css property can access through regular object.property - function parameter could take whole object from code - inherit parameter value on html using <html>{parameter.value}</html> - utilize object{{}} during JSX - if function parameter receive property as an object to access property need double dot {parameter.object.property} - u can send property to OtherJS function by <OtherJS property /> - u can object css style in function for JSX using and apply boolean on it Example: ```jsx= {display: parameter.property ? "block" : "none" } // if only one condition {color: !parameter.property && "%FF000" } ``` - [Higher order methods mention in video](https://dev.to/damcosset/higher-order-functions-in-jsx-4j8b) map return new array so remember add varaible for it ```*.js=+ const variable = array.map(function()); // => method on es6 array.map (() => <html></html> ); ``` - in React,key is require for map as an unique id <code>key={}</code> - toLocaleString() can utilize double bracket for styling <code>toLocaleString("en", {style: "currency", currency: "USD" })</code> - JSON can straight <code>export default</code> array if wanted ## Component and Class in React - ==IMPORTANT: method in class that use setState() should bind on constructor before call it== - ==IMPORTANT: calling parameter in class has to be this.props== - [Components and props](https://reactjs.org/docs/components-and-props.html) - [Classes in ES6](https://developer.mozilla.org/en-US/docs/Web/jsx/Reference/Classes) - [React.Component](https://reactjs.org/docs/react-component.html) ```jsx= import React from "react" // function App() { // return ( // <div> // <h1>Code goes here</h1> // </div> // ) // } class App extends React.Component { yourMethodHere(props) { this.props; } render() { const style = this.yourMethodHere() return ( <div> <h1>Code goes here</h1> </div> ) } } export default App ``` ## React State ```jsx= import React from "react" // https://scrimba.com/p/p4Mrt9/cQnMDHD class App extends React.Component { constructor() { super() this.state = { answer: "Yes" } } render() { return ( <div> <h1>Is state important to know? {this.state.answer}</h1> <ChildComponent answer={this.state.answer}/> </div> ) } } export default App ``` ### React setState - if using method from class, u should bind it on constructor ```jsx= import React from "react" class App extends React.Component { constructor() { super() this.state = { count: 0 } // bind handleclick this.handleClick = this.handleClick.bind(this) } // method handleClick() { this.setState(prevState => { return { count: prevState.count + 1 } }) } render() { return ( <div> <h1>{this.state.count}</h1> <button onClick={this.handleClick}>Change!</button> // <ChildComponent count={this.state.count}/> </div> ) } } export default App ``` - u can pass method as object property ## Event in React - [Events](https://reactjs.org/docs/events.html#supported-events) - event in React are camelCase ## React Lifecycle ```jsx= // https://engineering.musefind.com/react-lifecycle-methods-how-and-when-to-use-them-2111a1b692b1 // https://reactjs.org/blog/2018/03/29/react-v-16-3.html#component-lifecycle-changes class TodoList extends Component { constructor() { super() this.state = {} } static getDerivedStateFromProps(props, state) { // return the new, updated state based upon the props // https://reactjs.org/docs/react-component.html#static-getderivedstatefromprops // https://reactjs.org/blog/2018/06/07/you-probably-dont-need-derived-state.html } getSnapshotBeforeUpdate() { // create a backup of the current way things are // https://reactjs.org/docs/react-component.html#getsnapshotbeforeupdate } // componentWillMount() { // } componentDidMount() { // GET the data I need to correctly display } // componentWillReceiveProps(nextProps) { // if (nextProps.whatever !== this.props.whatever) { // // do something important here // } // } shouldComponentUpdate(nextProps, nextState) { // return true if want it to update // return false if not } // componentWillUpdate() { // } componentWillUnmount() { // teardown or cleanup your code before your component disappears // (E.g. remove event listeners) } render() { return ( <div> Code goes here </div> ) } } ``` ### componentDidUpdate() ```jsx= // https://scrimba.com/g/greacthooks // Uncaught Invariant Violation: Maximum update depth exceeded. This can happen when a component repeatedly calls setState inside componentWillUpdate or componentDidUpdate. React limits the number of nested updates to prevent infinite loops. import React from "react" import randomcolor from "randomcolor" class App extends React.Component { constructor() { super() this.state = { count: 0, color: "" } this.increment = this.increment.bind(this) this.decrement = this.decrement.bind(this) } increment() { this.setState(prevState => { return { count: prevState.count + 1 } }) } decrement() { this.setState(prevState => { return { count: prevState.count - 1 } }) } componentDidUpdate(prevProps, prevState) { if(prevState.count !== this.state.count) { const newColor = randomcolor() this.setState({color: newColor}) } } render() { return ( <div> <h1 style={{color: this.state.color}}>{this.state.count}</h1> <button onClick={this.increment}> Increment! </button> <button onClick={this.decrement}> Decrement! </button> </div> ) } } export default App ``` ## React Conditional Render ```jsx= import React, {Component} from "react" import Conditional from "./Conditional" class App extends Component { constructor() { super() this.state = { isLoading: true } } componentDidMount() { setTimeout(() => { this.setState({ isLoading: false }) }, 1500) } render() { return ( <div> {this.state.isLoading ? <h1>Loading...</h1> : <Conditional />} </div> ) } } export default App /* import React, {Component} from "react" import Conditional from "./Conditional" class App extends Component { constructor() { super() this.state = { isLoading: true } } componentDidMount() { setTimeout(() => { this.setState({ isLoading: false }) }, 1500) } render() { return ( <div> <Conditional isLoading={this.state.isLoading}/> </div> ) } } export default App */ ``` Conditional.js ```jsx= import React from "react" function Conditional(props) { return <h1>Some cool stuff about conditional rendering</h1> } export default Conditional /* import React from "react" function Conditional(props) { // condition ? statement if true : statement if false if(props.isLoading === true) { return ( <h1>Loading...</h1> ) } return ( <h1>Some cool stuff about conditional rendering</h1> ) } export default Conditional */ ``` && Operator ```jsx= import React, {Component} from "react" import Conditional from "./Conditional" class App extends Component { constructor() { super() this.state = { unreadMessages: ["a", "b", "c"] } } // && // false && false render() { return ( <div> { this.state.unreadMessages.length >= 0 && <h2>You have {this.state.unreadMessages.length} unread messages!</h2> } </div> ) } } export default App ``` ## Fetching data from api with React - [Fetch api React](https://reactjs.org/docs/faq-ajax.html) ```jsx= import React, {Component} from "react" // https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch // https://swapi.co/ // https://medium.com/jsx-scene/master-the-jsx-interview-what-is-a-promise-27fc71e77261 class App extends Component { constructor() { super() this.state = { loading: false, character: {} } } // following api cant be used componentDidMount() { this.setState({loading: true}) fetch("https://swapi.co/api/people/1") .then(response => response.json()) .then(data => { this.setState({ loading: false, character: data }) }) } render() { const text = this.state.loading ? "loading..." : this.state.character.name return ( <div> <p>{text}</p> </div> ) } } export default App ``` ## Form in React - [Form in React](https://reactjs.org/docs/forms.html) - [Formik module](https://jaredpalmer.com/formik/docs/overview) for form to save ur ass ```jsx= import React, {Component} from "react" class App extends Component { constructor() { super() this.state = { firstName: "", lastName: "" } this.handleChange = this.handleChange.bind(this) } handleChange(event) { // const {name, value} = event.target // this.setState({ // [name]: value // }) this.setState({ [event.target.name]: event.target.value }) } render() { return ( <form> <input type="text" value={this.state.firstName} name="firstName" placeholder="First Name" onChange={this.handleChange} /> <br /> <input type="text" value={this.state.lastName} name="lastName" placeholder="Last Name" onChange={this.handleChange} /> <h1>{this.state.firstName} {this.state.lastName}</h1> </form> ) } } export default App ``` ### Form Example ```jsx= import React, {Component} from "react" class App extends Component { constructor() { super() this.state = { firstName: "", lastName: "", isFriendly: false, gender: "", favColor: "blue" } this.handleChange = this.handleChange.bind(this) } handleChange(event) { const {name, value, type, checked} = event.target type === "checkbox" ? this.setState({ [name]: checked }) : this.setState({ [name]: value }) } render() { return ( <form onSubmit={this.handleSubmit}> <input type="text" value={this.state.firstName} name="firstName" placeholder="First Name" onChange={this.handleChange} /> <br /> <input type="text" value={this.state.lastName} name="lastName" placeholder="Last Name" onChange={this.handleChange} /> { /** * Other useful form elements: * * <textarea /> element * <input type="checkbox" /> * <input type="radio" /> * <select> and <option> elements */ } <textarea value={"Some default value"} onChange={this.handleChange} /> <br /> <label> <input type="checkbox" name="isFriendly" checked={this.state.isFriendly} onChange={this.handleChange} /> Is friendly? </label> <br /> <label> <input type="radio" name="gender" value="male" checked={this.state.gender === "male"} onChange={this.handleChange} /> Male </label> <br /> <label> <input type="radio" name="gender" value="female" checked={this.state.gender === "female"} onChange={this.handleChange} /> Female </label> {/* Formik */} <br /> <label>Favorite Color:</label> <select value={this.state.favColor} onChange={this.handleChange} name="favColor" > <option value="blue">Blue</option> <option value="green">Green</option> <option value="red">Red</option> <option value="orange">Orange</option> <option value="yellow">Yellow</option> </select> <h1>{this.state.firstName} {this.state.lastName}</h1> <h2>You are a {this.state.gender}</h2> <h2>Your favorite color is {this.state.favColor}</h2> <button>Submit</button> </form> ) } } export default App ``` ## React Container & Component(Using Exercise - React Form Pratice) :::spoiler App.js ```jsx= // https://medium.com/@dan_abramov/smart-and-dumb-components-7ca2f9a7c7d0 import React, {Component} from "react" import Form from "./FormContainer" function App() { return ( <Form /> ) } export default App ``` ::: :::spoiler FormComponent.js ```jsx= import React from "react" function FormComponent(props) { return ( <main> <form> <input name="firstName" value={props.data.firstName} onChange={props.handleChange} placeholder="First Name" /> <br /> <input name="lastName" value={props.data.lastName} onChange={props.handleChange} placeholder="Last Name" /> <br /> <input name="age" value={props.data.age} onChange={props.handleChange} placeholder="Age" /> <br /> <label> <input type="radio" name="gender" value="male" checked={props.data.gender === "male"} onChange={props.handleChange} /> Male </label> <br /> <label> <input type="radio" name="gender" value="female" checked={props.data.gender === "female"} onChange={props.handleChange} /> Female </label> <br /> <select value={props.data.destination} name="destination" onChange={props.handleChange} > <option value="">-- Please Choose a destination --</option> <option value="germany">Germany</option> <option value="norway">Norway</option> <option value="north pole">North Pole</option> <option value="south pole">South Pole</option> </select> <br /> <label> <input type="checkbox" name="isVegan" onChange={props.handleChange} checked={props.data.isVegan} /> Vegan? </label> <br /> <label> <input type="checkbox" name="isKosher" onChange={props.handleChange} checked={props.data.isKosher} /> Kosher? </label> <br /> <label> <input type="checkbox" name="isLactoseFree" onChange={props.handleChange} checked={props.data.isLactoseFree} /> Lactose Free? </label> <br /> <button>Submit</button> </form> <hr /> <h2>Entered information:</h2> <p>Your name: {props.data.firstName} {props.data.lastName}</p> <p>Your age: {props.data.age}</p> <p>Your gender: {props.data.gender}</p> <p>Your destination: {props.data.destination}</p> <p>Your dietary restrictions:</p> <p>Vegan: {props.data.isVegan ? "Yes" : "No"}</p> <p>Kosher: {props.data.isKosher ? "Yes" : "No"}</p> <p>Lactose Free: {props.data.isLactoseFree ? "Yes" : "No"}</p> </main> ) } export default FormComponent ``` ::: :::spoiler FormContainer.js ```jsx= import React, {Component} from "react" import FormComponent from "./FormComponent" class Form extends Component { constructor() { super() this.state = { firstName: "", lastName: "", age: "", gender: "", destination: "", isVegan: false, isKosher: false, isLactoseFree: false } this.handleChange = this.handleChange.bind(this) } handleChange(event) { const {name, value, type, checked} = event.target type === "checkbox" ? this.setState({ [name]: checked }) : this.setState({ [name]: value }) } render() { return( <FormComponent handleChange={this.handleChange} data={this.state} /> ) } } export default Form ``` ::: ## Vocabulary Props = Property ## Exercise in Scrimba(self-code) :::spoiler Exercise - Mapping Components Practice App.js ```jsx= function App() { /* Old School Method const productsList = products.map (function(detail) { return <Product key = {detail.id} name = {detail.name} price = {detail.price} desc = {detail.description} /> } ) */ const productsList = products.map (detail => <Product key= {detail.id} name = {detail.name} price = {detail.price} desc = {detail.description} /> ); return ( <div> {productsList} </div> ) } ``` Product.js ```jsx= function Product(props) { return ( <div> <p>Name:{props.name}</p> <p>Price:{props.price}</p> <p>Desc:{props.desc}</p><br /> </div> ) } ``` Example from Scrimba **App.js** ```jsx= function App() { const productComponents = productsData.map(item => <Product key={item.id} product={item}/>) return ( <div> {productComponents} </div> ) } ``` **Product.js** ```jsx= function Product(props) { return ( <div> <h2>{props.product.name}</h2> <p>{props.product.price.toLocaleString("en-US", { style: "currency", currency: "USD" })} - {props.product.description}</p> </div> ) } ``` ::: :::spoiler Exercise - React State Practice ```jsx= import React from "react" // Challenge: // Given an incomplete class-based component without a constructor, // add a constructor and initialize state to fix the broken component. class App extends React.Component { constructor() { super() this.state = { name: "Nantou", age: 16, } } render () { return ( <div> <h1>{this.state.name}</h1> <h3>{this.state.age} years old</h3> </div> ) } } export default App ``` ::: :::spoiler Exercise - React ToDo app Phase 6 App.js ```jsx= /** * Let's make it so our checkbox can actually mark our todo as complete or incomplete! * This challenge is a little more involved than some of the past ones. Check the comments * in the code for some help on accomplishing this one * * Challenge: * 1. Create an event handler in the App component for when the checkbox is clicked (which is an `onChange` event) * a. This method will be the trickest part. Check the comments in the stubbed-out method below for some pseudocode to help guide you through this part * 2. Pass the method down to the TodoItem component * 3. In the TodoItem component, make it so when the `onChange` event happens, it calls the `handleChange` method and passes the id of the todo into the function */ import React from "react" import TodoItem from "./TodoItem" import todosData from "./todosData" class App extends React.Component { constructor() { super() this.state = { todos: todosData } this.handleChange = this.handleChange.bind(this) } handleChange(id) { this.setState(prevState => { const updatedTodos = prevState.todos.map(todo => { if (todo.id === id) { return { ...todo, completed: !todo.completed } } return todo }) return { todos: updatedTodos } }) } render() { const todoItems = this.state.todos.map(item => <TodoItem key={item.id} item={item} handleChange={this.handleChange}/>) return ( <div className="todo-list"> {todoItems} </div> ) } } export default App ``` Old School App.js ```jsx= handleChange(id) { this.setState(function (prevState) { const updateItem = prevState.todos.map(function (todo) { if (todo.id === id) { return { ...todo, completed: !todo.completed } } return todo; }); return { todos: updateItem } }); } ``` TodoItem.js ```jsx= import React from "react" function TodoItem(props) { return ( <div className="todo-item"> <input type="checkbox" checked={props.item.completed} onChange={() => props.handleChange(props.item.id)} /> <p>{props.item.text}</p> </div> ) } export default TodoItem ``` ::: :::spoiler Exercise - React Conditional Render Practice ```jsx= import React from "react" /* Challenge: Given a stateless functional component: 1. Follow the steps necessary to add state to it, // class-based component // constructor method 2. Have state keep track of whether the user is logged in or not // isLoggedIn: Boolean (true or false) 3. Add a button that logs the user in/out // event listener (onClick) a. extra challenge - make the button display "log in" if they're not logged in and "log out" if they are // Conditional Rendering 4. Display text that says "Logged in" if the user is logged in, or "Logged out" if they're not. // Conditional Rendering */ class App extends React.Component { constructor() { super() this.state = { isLoggedIn: false } this.handleClick = this.handleClick.bind(this) } handleClick() { this.setState(prevState => { return { isLoggedIn: !prevState.isLoggedIn } }) } render() { let buttonText = this.state.isLoggedIn ? "LOG OUT" : "LOG IN" let displayText = this.state.isLoggedIn ? "Logged in" : "Logged out" return ( <div> <button onClick={this.handleClick}>{buttonText}</button> <h1>{displayText}</h1> </div> ) } } export default App ``` ::: :::spoiler Exercise - React ToDo App: Phase 7 ==App.js== ```jsx= /** * Let's make it so our checkbox can actually mark our todo as complete or incomplete! * This challenge is a little more involved than some of the past ones. Check the comments * in the code for some help on accomplishing this one * * Challenge: * 1. Create an event handler in the App component for when the checkbox is clicked (which is an `onChange` event) * a. This method will be the trickest part. Check the comments in the stubbed-out method below for some pseudocode to help guide you through this part * 2. Pass the method down to the TodoItem component * 3. In the TodoItem component, make it so when the `onChange` event happens, it calls the `handleChange` method and passes the id of the todo into the function */ import React from "react" import TodoItem from "./TodoItem" import todosData from "./todosData" import randomcolor from "randomcolor" class App extends React.Component { constructor() { super() this.state = { todos: todosData, color: "" } this.handleChange = this.handleChange.bind(this) } handleChange(id) { this.setState(prevState => { const newColor = randomcolor() const updatedTodos = prevState.todos.map(todo => { if (todo.id === id) { todo.completed = !todo.completed todo.color = newColor } return todo }) return { todos: updatedTodos } }) } render() { const todoItems = this.state.todos.map(item => <TodoItem key={item.id} item={item} handleChange={this.handleChange}/>) return ( <div className="todo-list"> {todoItems} </div> ) } } export default App ``` ==ToDoItem.js== ```jsx= /** * Challenge: Style the completed todo items differently from the incomplete items. */ import React from "react" function TodoItem(props) { return ( <div className="todo-item"> <input type="checkbox" checked={props.item.completed} onChange={() => props.handleChange(props.item.id)} /> <p style ={props.item.completed ? {color:props.item.color} : {color:"#000000"}}>{props.item.text}</p> </div> ) } export default TodoItem ``` ==Answer:ToDoItem.js== ```jsx= /** * Challenge: Style the completed todo items differently from the incomplete items. */ import React from "react" function TodoItem(props) { const completedStyle = { fontStyle: "italic", color: "#cdcdcd", textDecoration: "line-through" } return ( <div className="todo-item"> <input type="checkbox" checked={props.item.completed} onChange={() => props.handleChange(props.item.id)} /> <p style={props.item.completed ? completedStyle: null}>{props.item.text}</p> </div> ) } export default TodoItem ``` ::: :::spoiler Exercise - React Form Practice ```jsx= import React, {Component} from "react" /** * Challenge: Wire up the partially-finished travel form so that it works! * Remember to use the concept of controlled forms * https://reactjs.org/docs/forms.html * * All information should be populating the text below the form in real-time * as you're filling it out * * This exercise is adapted from the V School curriculum on vanilla JS forms: * https://coursework.vschool.io/travel-form/ * * All of our challenges and learning resources are open for the public * to play around with and learn from at https://coursework.vschool.io */ class App extends Component { constructor() { super() this.state = { firstName: "", lastName: "", age: "", gender: "", destination: "", isVegan: false, isKosher: false, isLactoseFree: false } this.handleChange = this.handleChange.bind(this) } handleChange(event) { const {name, value, type, checked} = event.target type === "checkbox" ? this.setState({ [name]: checked }) : this.setState({ [name]: value }) } render() { return ( <main> <form> <input name="firstName" value={this.state.firstName} onChange={this.handleChange} placeholder="First Name" /> <br /> <input name="lastName" value={this.state.lastName} onChange={this.handleChange} placeholder="Last Name" /> <br /> <input name="age" value={this.state.age} onChange={this.handleChange} placeholder="Age" /> <br /> <label> <input type="radio" name="gender" value="male" checked={this.state.gender === "male"} onChange={this.handleChange} /> Male </label> <br /> <label> <input type="radio" name="gender" value="female" checked={this.state.gender === "female"} onChange={this.handleChange} /> Female </label> <br /> <select value={this.state.destination} name="destination" onChange={this.handleChange} > <option value="">-- Please Choose a destination --</option> <option value="germany">Germany</option> <option value="norway">Norway</option> <option value="north pole">North Pole</option> <option value="south pole">South Pole</option> </select> <br /> <label> <input type="checkbox" name="isVegan" onChange={this.handleChange} checked={this.state.isVegan} /> Vegan? </label> <br /> <label> <input type="checkbox" name="isKosher" onChange={this.handleChange} checked={this.state.isKosher} /> Kosher? </label> <br /> <label> <input type="checkbox" name="isLactoseFree" onChange={this.handleChange} checked={this.state.isLactoseFree} /> Lactose Free? </label> <br /> <button>Submit</button> </form> <hr /> <h2>Entered information:</h2> <p>Your name: {this.state.firstName} {this.state.lastName}</p> <p>Your age: {this.state.age}</p> <p>Your gender: {this.state.gender}</p> <p>Your destination: {this.state.destination}</p> <p>Your dietary restrictions:</p> <p>Vegan: {this.state.isVegan ? "Yes" : "No"}</p> <p>Kosher: {this.state.isKosher ? "Yes" : "No"}</p> <p>Lactose Free: {this.state.isLactoseFree ? "Yes" : "No"}</p> </main> ) } } export default App ``` ::: - [Exercise - MemeGenerator](https://scrimba.com/p/p7P5Hd/cob4c-ba9977f98d4d) I lazy to copy and paste lol ## Things may not include in Scrimba Tutorial :::spoiler ```jsx= import React, {Component} from "react" class App extends Component { // Change to use class properties constructor() { super() this.state = { firstName: "" } this.handleChange = this.handleChange.bind(this) } // Change to use arrow functions handleChange(event) { const { name, value } = event.target this.setState({ [name]: value }) } render() { return ( <main> <form> <input type="text" name="firstName" value={this.state.firstName} onChange={this.handleChange} placeholder="First Name" /> </form> <h1>{this.state.firstName}</h1> </main> ) } } export default App /** * Other modern/advanced React features/topics to learn: * * Official React Context API - https://reactjs.org/docs/context.html * Error Boundaries - https://reactjs.org/docs/error-boundaries.html * render props - https://reactjs.org/docs/render-props.html * Higher Order Components - https://reactjs.org/docs/higher-order-components.html * React Router - https://reacttraining.com/react-router/core/guides/philosophy * React Hooks - https://reactjs.org/docs/hooks-intro.html * React lazy, memo, and Suspense - https://reactjs.org/blog/2018/10/23/react-v-16-6.html */ ``` ::: ## Other CheatSheet [**ES6 CheatSheet**](https://hackmd.io/@iS7O2LlgQnCDVpTMoIs94g/ES6CheatSheet) [**Higher order methods mention in video**](https://dev.to/damcosset/higher-order-functions-in-jsx-4j8b) [**V School**](https://coursework.vschool.io/) [**Project Idea 1**](https://medium.freecodecamp.org/every-time-you-build-a-to-do-list-app-a-puppy-dies-505b54637a5d) [**Project Idea 2**](https://medium.freecodecamp.org/want-to-build-something-fun-heres-a-list-of-sample-web-app-ideas-b991bce0ed9a) [**Project Idea 3**](https://medium.freecodecamp.org/summer-is-over-you-should-be-coding-heres-yet-another-list-of-exciting-ideas-to-build-a95d7704d36d) [React-Bulma-Component](https://couds.github.io/react-bulma-components/?path=/story/button--as-another-react-element) ## Reference Most code reference from [Scrimba React tutorial](https://scrimba.com/g/glearnreact) # React Router - [Stack overflow router](https://stackoverflow.com/questions/37295377/how-to-navigate-from-one-page-to-another-in-react-js) - [Button render as link - github pull](https://github.com/couds/react-bulma-components/issues/55) - [Router render-client and sever side](https://stackoverflow.com/questions/27928372/react-router-urls-dont-work-when-refreshing-or-writing-manually) - [React router ] # React Hook - useState() part 1 ```jsx= import React, {useState} from "react" function App() { const [answer, ???] = useState("Yes") return ( <div> <h1>Is state important to know? {answer}</h1> </div> ) } // class App extends React.Component { // constructor() { // super() // this.state = { // answer: "Yes" // } // } // render() { // return ( // <div> // <h1>Is state important to know? {this.state.answer}</h1> // </div> // ) // } // } export default App ``` - useState Part 2 ```jsx= import React, {useState} from "react" // Convert the class below to a functional component that uses the useState hook to initalize a count vartiable to 0 and display the count on the screen. // Don't worry about the part where the button changes the count quite yet, that's what you're here to learn about! function App() { const [count, setCount] = useState(0) const [answer, setAnswer] = useState("Yes") function increment() { setCount(prevCount => prevCount + 1) } function decrement() { setCount(prevCount => prevCount - 1) } // return ( // <div> // <h1>{count}</h1> // <button onClick={() => setCount(prevCount => prevCount + 1)}>Change!</button> // </div> // ) return ( <div> <h1>{count}</h1> <button onClick={increment}>Increment</button> <button onClick={decrement}>Decrement</button> </div> ) } // class App extends React.Component { // constructor() { // super() // this.state = { // count: 0, // answer: "Yes" // } // } // render() { // return ( // <div> // <h1>{this.state.count}</h1> // <button>Change!</button> // </div> // ) // } // } export default App ``` - useEffect part 1 ```jsx= import React, {useState, useEffect} from "react" import randomcolor from "randomcolor" function App() { const [count, setCount] = useState(0) const [color, setColor] = useState("") function increment() { setCount(prevCount => prevCount + 1) } function decrement() { setCount(prevCount => prevCount - 1) } useEffect(() => { setColor(randomcolor()) }, [count]) return ( <div> <h1 style={{color: color}}>{count}</h1> <button onClick={increment}>Increment</button> <button onClick={decrement}>Decrement</button> </div> ) } export default App ``` - useEffect part 2 ```jsx= import React, {useState, useEffect} from "react" import randomcolor from "randomcolor" function App() { const [count, setCount] = useState(0) const [color, setColor] = useState("") useEffect(() => { const intervalId = setInterval(() => { // setCount(prevCount => prevCount + 1) }, 1000) return () => clearInterval(intervalId) }, []) useEffect(() => { setColor(randomcolor()) }, [count]) return ( <div> <h1 style={{color: color}}>{count}</h1> </div> ) } export default App ```