I don’t use React very often, so whenever I need to do the smallest thing in React, I have to look at documentation, tutorials, or post a problem on a forum.

That’s why I decided to make this memory aid. Given that my memory isn’t that great, I thought why not use all the concepts I know about React to make a horrible memory aid.

So I can read it from time to time to strengthen my understanding of React.

If you have ideas or suggestions, please don’t hesitate to do so in the comments section.

The memo

Create a React application

/ / create
npx create-react-app my-app-name

/ / start
cd my-app-name
yarn start

// http://localhost:3000
/** * The first React function component * does not need to import React from 'React' (since React 17) * must start with a capital letter * must return JSX **/
(src/App.js)
// React component
function App(){
  return <h1>Hello World</h1>
} 

export default App;
Copy the code

How does this component render to the browser? The main project file is SRC /index.js and there are instructions to render the component

ReactDOM.render(<App />.document.getElementById('root'))
Copy the code

The App component will then be rendered in the public/index.html ‘root’ div

Import components Components are created in separate files. Each component needs to be exported and then imported

function Greeting(){
    return <h1>Hello World</h2>
}
export default Greeting
Copy the code

You can then import the component

import Greeting from './Gretting'

function App(){
    return <Greeting />
}
Copy the code

Or name export…

export function Greeting(){
    return <h1>Hello World</h2>
}
Copy the code

You can then import the component

import {Greeting} from './Gretting'
//BEM naming convention
return (
<div className="app">
  <h1 className="app_title">Welcome to my application: {appTitle}</h1>
  <div className="product">
    <h1 className="product__name--large">Product name: {product.name}</h1>
<h1 className="product__name--small">Nick name: {product.nickName}</h1>
    <p className="product__description">Product description: {product.description}
  </div>
<div>
)
Copy the code

JSX rule returns a single element (only one parent element)

// not valid
return <h1>Hello world</h1><h2>Hi!</h2>

return (
    <>
        <h1>Hello World</h1>
        <h2>Hi!</h2>
    </>
)
Copy the code

Use className instead of class all attribute names need to be humped

// not valid
return (
    <div class="title">
        Hello World
    </div>
)

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

Copy the code

Close each element

return (
    <img src="http:example.com/image.jpg" />
    <input type="text" name="first_name" />
)
Copy the code

Nested components

// 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 />
      </>)}Copy the code

Components of CSS

(src/App.css)
h1 {
    color: red;
}

(src/App.js)
Copy the code

Importing a CSS File

import './App.css'

function App(){
  return <h1>Hello World</h1>
} 
Copy the code

Inline CSS

function App(){
  return <h1 style={{ color: 'red' }}>Hello World</h1>
} 
Copy the code

JavaScript in JSX must enclose {} as an expression (return value)

function App(){
    const name = 'Mike'
    return (
      <>
          <h1>Hello {name}</h1>
          <p>{name === 'Mike' ? '(admin)': '(user)'}</p>
      </>)}Copy the code

Component properties (items)

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>
}
Copy the code

Sub-component props (slots)

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>)}Copy the code

Default item value

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

Person.defaultProps = {
    name: 'No name'.age: 0,}Copy the code

The list of

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>)}Copy the code

Lists with keys (for internal React reference)

function App(){
    return (
        people.map(person= > {
            return <Person key={person.id} name={person.name} age={person.age}/>}}))Copy the code

Item object deconstruction

function App(){
  return people.map(person= > <Person key={person.id} {. person} / >)}const Person = (name, age) = > {
  return (
      <h1>Name: {name}, Age: {age}</h1>)}Copy the code

Click on the event

const clickHandler = () = > alert('Hello World')
function App(){
    return (
        <>
            <h1>Welcome to my app</h1>
            <button onClick={clickHandler}>Say Hi</button>
        </>)}Copy the code

Or inline…

function App(){
    return (
        <>
            <h1>Welcome to my app</h1>
            <button onClick={() = > alert('Hello World') }>Say Hi</button>
        </>)}Copy the code

To pass arguments, we need to use the arrow function

const clickHandler = (message) = > alert(message)
function App(){
    return (
        <>
            <h1>Welcome to my app</h1>
            <button onClick={()= > clickHandler('Hello World')}>Say Hi</button>
        </>)}Copy the code

E is for the event parameter

const clickHandler = (e) = > console.log(e.target)
function App(){
    return (
        <>
            <h1>Welcome to my app</h1>
            <button onClick={()= > clickHandler('Hello World')}>Say Hi</button>
        </>)}Copy the code

Pass events from child to parent

function Todo({item, onDelete}) {
    return (
      <div>
        {item}
        <button onClick={()= > onDelete(item)} 
      </div>) } function Todos() { const handleDelete = (todo) => { const newTodos = todos.filter(item => item ! == todo) setTodos(() => newTodos) } return ( {todos.map(todo => (<Todo item={todo} onDelete={handleDelete}/>})}Copy the code

The purpose of using the state hook useState is to process reactive data. Any data that changes in an application is called state. When the state changes, you need to react to update the UI.

Hooks always start with the prefix “use” must only be called in React components/functions must be called at the top level of function components cannot be conditionally called Declare useState returns an array of 2: [state value, set state function]

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;
Copy the code

UseState and objects

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>
  </>
};
Copy the code

SetState function form

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>
    </>)}Copy the code

Using Effects In React, you might want to execute code after a lifecycle event or side effect.

By default, the useEffect function is executed after each re-rendering. You can then execute the code each time a component is updated.

import React, { useEffect } from 'react';

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

UseEffect dependency list What if you only want to execute the code on the first rendering or only on specific state changes? You can use the useEffect function and send an array of dependencies as arguments.

UseEffect is run only if state is in the dependency list. If the list is empty [], useEffect will run only during initial rendering.

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.
Copy the code

UseEffect cleanup Function What if you want to execute code every time you unload a component?

To execute code only when the component is unloaded/destroyed, you need to add a “return” statement to the useEffect function.

useEffect(() = >  { 
    const timer = window.setInterval(() = > { 
        setCount(count= > count + 1)},1000)
    return () = > clearInterval(timer)
}, [])
Copy the code

The code “clearInterval(timer)” is executed only before the component is removed (unloaded) from the UI

Conditions apply colours to a drawing

function DisplayGreeting() {
    const [name, setName] = useState('Mike')
    if (name === 'Mike') {
        return <h1>Hello admin {name}</h1> 
    }
    return <h1>Hello user {name}</h1> 
}
Copy the code

Inline If – Else

  return (
    <div>
      The user is <b>{isLoggedIn ? 'currently' : 'not'}</b> logged in.
    </div>
  );
}
Copy the code

Inline logical && operators. Truthy = Not: 0, “”, NULL, undefined, and NaN are displayed only if the first expression is true

  function DisplayUserInfo({active}) {
    return (
      <div>
        { active && <h1>User is active</h1>}
      </div>
    );
}
Copy the code

Multiple inline Ifs

<span className={count === 0 && 'text-gray-500' || count > 0 && 'text-green-500' || count < 0 && 'text-red-500'}>{count}</span>
Copy the code

In the form of

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;
Copy the code

The useRef reference is used primarily to locate DOM elements. But it can also be used to hold/preserve mutable values between each render. UseRef does not trigger rerendering (such as useState).

const UseRefBasics = () = > {
  const refContainer = useRef(null)
  const handleSubmit = (e) = > {
    e.preventDefault()
    console.log(refContainer.current.value)
  }

  useEffect(() = > {
    refContainer.current.focus()
  }, [])

  return (
    <div>
      <form className="form" onSubmit={handleSubmit}>
        <div>
          <input ref={refContainer} type="text" />
          <button type="submit">Submit</button>
        </div>
      </form>
    </div>)};Copy the code

Conclusion That’s all for today. We still have a lot of work to do, if you feel, please follow me!