React (work in progress) Cheat sheet
Tags: javascript, react, beginners, tutorial
Published: 2021-04-16 15:23:18

---
title: React (work in progress) Cheat sheet
published: true
description: 
tags: javascript, react, beginner, tutorial
cover_image: https://dev-to-uploads.s3.amazonaws.com/uploads/articles/r3ui703pme0meo82pu5o.png
series: React Cheat Sheet
---

I don't use React often and so whenever I need to do even the smallest thing in React, I have to check out the documentation, a tutorial, or post a question on a forum.

That's why I decided to do this memory aid and given that my memory is not that good I thought why not make a monstrous memory aid with all the concepts I know about React.

So I can read it from time to time and thereby strengthen my knowledge of React.

It will take couples of days to put all that together so every day I will post an updated Cheat Sheet version until the final version.

If you have ideas or recommendation do not hesitate and do so in the comments section.


<h2>React Cheat Sheet (draft day 2)</h2>
&nbsp;

<h4>Create a React App</h4>
```js
// Create a new app
npx create-react-app my-app-name

// Run the created app
cd my-app-name
yarn start

// http://localhost:3000
```

<h3>First React functional Component</h3>
- No need to import React from 'react' (since React 17)
- Must have uppercase first letter
- Must return JSX

(src/App.js)
```react
// React component
function App(){
  return <h1>Hello World</h1>
} 

export default App;
```
How this component get render to the browser? The main project file is src/index.js and in that file there are instruction to render the component
```react
ReactDOM.render(<App />, document.getElementById('root'))
```
The App component will then be rendered inside public/index.html 'root' div

<h3>Import Component</h3>
Component will be created in separate files. Each component need to be export and then import
```js
function Greeting(){
    return <h1>Hello World</h2>
}
export default Greeting
```
This component can then be import
```js
import Greeting from './Gretting'

function App(){
    return <Greeting />
}
```
or name export...
```js
export function Greeting(){
    return <h1>Hello World</h2>
}
```
This component can then be import
```js
import {Greeting} from './Gretting'
```

<h3>JSX Rules</h3>
Return a single element (only one parent element)
```react
// not valid
return <h1>Hello world</h1><h2>Hi!</h2>

// valid with fragment. 
return (
    <>
        <h1>Hello World</h1>
        <h2>Hi!</h2>
    </>
)
// Noted the parenthesis for multi-line formatting
```
Use className instead of class
Also all attribute name need to be camelCase
```react
// not valid
return (
    <div class="title">
        Hello World
    </div>
)

// valid
return (
    <div className="title">
    </div>
)

```
Close every element
```react
return (
    <img src="http:example.com/image.jpg" />
    <input type="text" name="first_name" />
)
```
<h3>Nested Components</h3>
```react
// Arrow function shorthand component
const Person = () => <h1>Mike Taylor</h1>

// Arrow function component
const Message = () => {
    return <h1>Hello</h1>
}

// Function component
function HelloWorld(){
  return (
      <>
          <Message />
          <Person />
      </>
  )
} 
```

<h3>Component CSS</h3>
(src/App.css)
```css
h1 {
    color: red;
}

```
(src/App.js)
Import the CSS file
```react
import './App.css'

function App(){
  return <h1>Hello World</h1>
} 
```

<h3>Inline CSS</h3>
```react
function App(){
  return <h1 style={{ color: 'red' }}>Hello World</h1>
} 
```
<h3>Javascript in JSX</h3>
- Enclose between {}
- Must be an expression (return a value)
```react
function App(){
    const name = 'Mike'
    return (
      <>
          <h1>Hello {name}</h1>
          <p>{name === 'Mike' ? '(admin)': '(user)'}</p>
      </>
    )
} 
```

<h3>Component Properties (Props)</h3>
```react
function App()
    return <Person name='Mike' age={29} />
} 

const Person = (props) => {
    return <h1>Name: {props.name}, Age: {props.age}</h1>
}

// or props object deconstructing
const Person = ({name, age}) => {
    return <h1>Name: {name} Age: {age}</h1>
}
```
<h3>Children Props (slot)</h3>
```react
function App()
    return (
        <Person name='Mike' age={29}>
            Hi, this is a welcome message
        </Person>
    )
} 

const Person = (props) => {
    return (
        <h1>Name: {props.name}, Age: {props.age}</h1>
        <p>{props.children}</p>
    )
}

// or props object deconstructing
const Person = ({name, age, children}) => {
    return (
        <h1>Name: {name} Age: {age}</h1>
        <p>{children}</p>
    )
}
```
<h3>List</h3>
```react
const people = [
  {id: 1, name: 'Mike', age: 29},
  {id: 2, name: 'Peter', age: 24},
  {id: 3, name: 'John', age: 39},
]
function App(){
    return (
        people.map(person => {
            return <Person name={person.name} age={person.age}/>
        })
    )
} 

const Person = (props) => {
  return (
      <h1>Name: {props.name}, Age: {props.age}</h1>
  )
}
```
<h3>List with key (for React internal reference)</h3>
```react
function App(){
    return (
        people.map(person => {
            return <Person key={person.id} name={person.name} age={person.age}/>
        })
     )
} 
```

<h3>Props object deconstructing</h3>
```react
function App(){
  return people.map(person => <Person key={person.id} {...person} />)
}

const Person = (name, age) => {
  return (
      <h1>Name: {name}, Age: {age}</h1>
  )
} 
```

<h3>Click Event</h3>
```react
const clickHandler = () => alert('Hello World')
function App(){
    return (
        <>
            <h1>Welcome to my app</h1>
            <button onClick={clickHandler}>Say Hi</button>
        </> 
    )
} 
```
or inline...
```react
function App(){
    return (
        <>
            <h1>Welcome to my app</h1>
            <button onClick={ () => alert('Hello World') }>Say Hi</button>
        </>
     )
} 
```
To pass arguments we need to use arrow function
```react
const clickHandler = (message) => alert(message)
function App(){
    return (
        <>
            <h1>Welcome to my app</h1>
            <button onClick={() => clickHandler('Hello World')}>Say Hi</button>
        </> 
    )
} 
```

e for event arguments
```react
const clickHandler = (e) => console.log(e.target)
function App(){
    return (
        <>
            <h1>Welcome to my app</h1>
            <button onClick={() => clickHandler('Hello World')}>Say Hi</button>
        </> 
    )
} 
```

<h3>useState Hook</h3>
- Hook always start with use prefix
- Must be invoke in the component/function body
- Declaration cannot be call conditionally
- useState return an array of 2 [state value, set state function]

```js
import React, {useState} from 'react';

const DisplayTitle = () => {
  const [title, setTitle] = useState('This is the Title')
  const handleClick = () => setTitle('New Title')
  return <>
    <h2>{title}</h2>
    <button type="button" className="btn" onClick={handleClick}>
      Change Title
    </button>
  </>
};

export default DisplayTitle;
```
<h3>useState with object</h3>
```js
const DisplayTitle = () => {
  const [person, setPerson] = useState({name: 'Mike', age: 29})
  const handleClick = () => setPerson({...person, age: 35})
  return <>
    <h2>{title}</h2>
    <button type="button" className="btn" onClick={handleClick}>
      Change Age
    </button>
  </>
};
```
<h3>setState functional form</h3>
```js
function Counter() {
  const [count, setCount] = useState(0)
  // Use a function to set State
  const increase = () => setCount(() => count + 1)
  return (
    <>
      <h1>Counter</h1>
      <p>{count}</p>
      <button onClick={increase} className='btn'> + </button>
      <button onClick={() => setCount(() => count - 1)} className='btn'> - </button>
    </>
  )
}
```
<h3>useEffect</h3>
By default useEffect run after every re-render
```js
import React, { useState, useEffect } from 'react';

function IncreaseValue() {
    const [value, setValue] = useState(0)
    useEffect(() => {
        document.title = `New value: ${value}` 
    })
    return <button onClick={() => setValue(value + 1)}>Increase</button>
}
```

<h3>Conditional useEffect</h3>
Conditional need to be place inside useEffect function
```js
useEffect(() => {
    if (value > 0) {
        document.title = `New value: ${value}` 
    }
})
```

<h3>useEffect Dependency List</h3>
useEffect will run only if state is in the Dependency List.
If the list is empty [] the useEffect will only run on initial render.
```js
useEffect(() => {
    document.title = `New value: ${value}` 
}, [])
// Noted the empty array. useEffect will then only run once on initial render

useEffect(() => {
    document.title = `New value: ${value}` 
}, [value])
// Will run each time 'value' state change.
```

<h3>useEffect cleanup function</h3>
This useEffect return function is execute each time the component unmount. Think at this return function like a cleaning code when the component unmount.
```js
useEffect(() =>  { 
    const timer = window.setInterval(() => { 
        setCount(count => count + 1)
    }, 1000)
    return () => clearInterval(timer)
}, [])
```

<h3>Component multiple returns</h3>
```js
function DisplayGreeting() {
    const [name, setName] = useState('Mike')
    if (name === 'Mike') {
        return <h1>Hello admin {name}</h1> 
    }
    return <h1>Hello user {name}</h1> 
}
```

<h3>Form</h3>
```js
const UserForm = () => {
  const [userName, setUserName] = useState('')
  const handleSubmit = (e) => {
    e.preventDefault()
    console.log(userName)
  }
return (
<>
    <form onSubmit={handleSubmit}>
      <input 
          value={userName} 
          onChange={(e) => setUserName(e.target.value)} 
          type="text" id="userName" 
          name="userName"
      />
       <button type="submit">Submit</button>
    </form>
</>
)
};

export default UserForm;
```

<h2>Conclusion</h2>
That's it for today. We still have a lot to do, so see you tomorrow... If you want to be sure to miss nothing click follow me!

I am new on twitter so if you want to make me happy
Follow me!: <a href="https://twitter.com/justericchapman?ref_src=twsrc%5Etfw" class="twitter-follow-button" data-show-count="false">Follow @justericchapman</a><script async src="https://platform.twitter.com/widgets.js" charset="utf-8"></script>