# REACT > FreeCodeCamp tuto (scrimba): > https://scrimba.com/learn/learnreact <br> ### ReactDOM and JSX > react virtual dom: > https://youtu.be/BYbgopx44vo > https://youtu.be/RquK3TImY9U > Virtual dom makes react work faster. It tracks where the change took place and updates only that part. There should be an *index.html*, *index.js* and maybe a style file in the simplest possible react project ![](https://i.imgur.com/ZeJcY0u.png) (1) ```html= <!-- index.html(1) --> <html> <head> <link rel="stylesheet" href="style.css"> </head> <body> <div id="root"></div> <script src="index.pack.js"></script> </body> </html> ``` In line 8, there's a div whose id is set to *root* ```javascript= // index.js(1) import React from "react"; import ReactDOM from "react-dom"; ReactDOM.render( <div> <h1>Highlight</h1> <p>This is a paragraph</p> <ul> <li>Thailand</li> <li>Japan</li> <li>Nordic Countries</li> </ul> </div>, document.getElementById("root") ); ``` The *render* method in line 6 takes in two arguments - thing to render and where it should place that. this will produce something like this - ![](https://i.imgur.com/ZP59WeZ.png) (1) ### using Functional components ```javascript= // index.js(2) function MyApp() { return ( <div> <h1>Highlight</h1> <p>This is a paragraph</p> <ul> <li>Thailand</li> <li>Japan</li> <li>Nordic Countries</li> </ul> </div> ); }; ReactDOM.render( <MyApp />, document.getElementById("root") ); ``` It's a general convention to keep all the components in seperate files. To do this, we can create a file inside a new directory named *components* ![](https://i.imgur.com/PCmGfbc.png) (2) The file should contain 1. imports 2. functional/class component 3. export ```javascript= // MyInfo.js(2) import React from "react" function MyInfo() { return ( <div> <h1>Highlight</h1> <p>This is a paragraph</p> <ul> <li>Thailand</li> <li>Japan</li> <li>Nordic Countries</li> </ul> </div> ) } export default MyInfo ``` Now the index.js should look like this - ```javascript= // index.js(2) import React from "react" import ReactDOM from "react-dom" import MyInfo from "./components/MyInfo" ReactDOM.render(<MyInfo />, document.getElementById("root")) ``` in line 6, we imported the component from MyInfo.js file. ### Parent Child Components We need to organise the components in their own files. Lets say, our project tree looks like this - ![](https://i.imgur.com/qB23pDj.png) (3) And the App.js file look like this - ```javascript= // App.js(3) import React from 'react'; import Navbar from './components/Navbar'; import MainContent from './components/MainContent'; import Footer from './components/Footer'; function App(){ return ( <main> <Navbar /> <MainContent /> <Footer /> </main> ); } export default App; ``` ### Inline Styling of Components The JSX elements can be decorated by adding styles. ```javascript= // Footer.js(3) import React from 'react'; function Footer(){ const footerStyle = { width:'100%', backgroundColor:'grey', color:'white', textAlign:'center', position:'fixed', left:0, bottom:0 }; return ( <div style={footerStyle}> <h4> thanks for stopping by </h4> </div> ) } export default Footer; ``` ### React Props Passing down the property values to components Say we have a list of products in a file `schoolProducts.js` ```javascript const products = [ { id: "1", name: "Pencil", price: 1, description: "Perfect for those who can't remember things! 5/5 Highly recommend." }, { id: "2", name: "Housing", price: 0, description: "Housing provided for out-of-state students or those who can't commute" }, { id: "3", name: "Computer Rental", price: 300, description: "Don't have a computer? No problem!" } ] export default products ``` and we have to display it like this - ![](https://i.imgur.com/DLZlzDs.png) <br/> We got a `product.js` file: ```javascript= import React from 'react'; const Product = (props) => { return ( <div> <h3> this be a {props.name} </h3> <p> {props.description} </p> <hr/> </div> ); }; export default Product; ``` And the `App.js` file ```javascript= import React from "react" import productsData from "./vschoolProducts" import Product from "./Product" function App() { const productsComponent = productsData.map(prod => <Product key={prod.id} name={prod.name} description={prod.description} />) return ( <div> {productsComponent} </div> ) } export default App ``` ### Class-based components In place of the functional component below ```javascript= function App() { return ( <div> <Header /> <Greeting /> </div> ) } ``` we can use a class based component - ```javascript= class App extends React.Component { render() { return ( <div> <Header username="dumbo"/> <Greeting /> </div> ) } } ``` ### State in class based component, we can store values for each components `App.js` ```javascript= class App extends React.Component { constructor(){ super() this.state = { name: "bumba", age: 23 } } render() { return ( <div> <h1>{this.state.name}</h1> <h3>{this.state.age} years old</h3> </div> ) } } export default App ``` > not to update states directly > To change state, use the setState method. Here's an `App.js` component that handles a click event and increments a state ```javascript= class App extends React.Component { constructor() { super() this.state = { count: 0 } this.handleChange = this.handleChange.bind(this) } handleChange() { this.setState(prevState => { count: prevState.count + 1 }) } render() { return ( <div> <h1>{this.state.count}</h1> <button onClick={this.handleChange}>Change!</button> </div> ) } } ``` Here, binding in the constructor is necessary. Or simply using arrow function would do - ```javascript= handleChange = () => { this.setState(prevState => { count: prevState.count + 1 }) console.log("called handleChange") } ``` No binding is required here. #### Changing State And Using Them > https://reactjs.org/docs/faq-functions.html > **sending function as param in react** > With React, typically you only need to bind the methods you pass to other components. For example, ```<button onClick={this.handleClick}>``` passes this.handleClick so you want to bind it. However, it is unnecessary to bind the render method or the lifecycle methods: we don’t pass them to other components. > https://reactjs.org/docs/handling-events.html > **handling events** We have this todo things with checkboxes ![](https://i.imgur.com/bSJ0anU.png) We need to respond to clicking on the boxes. Every item component in `todoItem.js` - ```javascript= 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)} // here the arrow function takes care of // the ids. Nothing is passed because by default // it takes in the event and we have nothing // to do with it. /> <p>{props.item.text}</p> </div> ) } export default TodoItem ``` In the `App.js` file we handle the clicking ```javascript= 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 // we must not change the original } } 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 ``` ### Lifecycle Methods > 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 * componentDidMount() ```javascript componentDidMount() { // runs the first time a component is created } ``` * componentDidUpdate() ```javascript componentDidUpdate() { // optional params -> prevProps, prevState // be careful to update state here // as it might trigger an infinite loop } ``` * componentWillReceiveProps() * shouldComponentUpdate() ```javascript shouldComponentUpdate(nextProps, nextState) { // return true if want it to update // return false if not } ``` * componentWillUnmount() ```javascript componentWillUnmount() { // teardown or cleanup your code before your component disappears // (E.g. remove event listeners) } ``` * getDerivedStateFromProps() ```javascript static getDerivedStateFromProps(props, state) { // return the new, updated state based upon the props // get props and set state acording to that // https://reactjs.org/blog/2018/06/07/you-probably-dont-need-derived-state.html } ``` * getSnapshotBeforeUpdate() ```javascript getSnapshotBeforeUpdate() { // create a backup of the current way things are } ``` > https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch > https://medium.com/javascript-scene/master-the-javascript-interview-what-is-a-promise-27fc71e77261