react

Wed, Mar 16, 2022 2-minute read

quick way to know react

Highly recommend this website Mmdn web docs.

basic operation

array.map()

const nums = [1, 2, 3, 4, 5]

const squares = nums.map(function(num) {
    return num * num
})
  • given an array of string, return an array where the first letter of each string is capitalized

const names = [“alice”, “bob”, “charlie”, “danielle”]

const capitalized = names.map(() => {
    return name[0].toUpperCase() + name.slice(1)
})
  • given an array of string, return an array of strings that wraps each of the original strings in an HTML-like <p></p> tag.

const names = [“alice”, “bob”, “charlie”, “danielle”]

const p = names.map((name) => {
    return `<p>${name}</p>`
})

react renders arrays

export default function App() {
    // const colors = ["Red", "Orange", "Yellow", "Green", "Blue", "Indigo", "Violet"]
    return (
        <div>
            {["Red", "Orange", "Yellow", "Green", "Blue", "Indigo", "Violet"]}

            {colors}
        </div>
    )
}

mapping components

  • jokesData.js
export default [
    {
        setup: "I got my daughter a fridge for her birthday.",
        punchline: "I can't wait to see her face light up when she opens it."
    },
    {
        setup: "How did the hacker escape the police?",
        punchline: "He just ransomware!"
    }
]
  • Joke.js
import React from "react"

export default function Joke(props) {
    return (
        <div>
            {props.setup && <h3> Setup: {props.setup}<h3>}
            <p>Punchline: {props.punchline}</p>
            <hr />
        </div>
    )
}

pass the necessary props to the Joke component in the .map() (and render the jokeElements array) so the jokes show up on the page again

import React from "react"
import Joke from "./joke"
import jokesData from "./jokesData"


export default function App() {
    console.log(jokesData)
    // [{setup:.........}]
    const jokeElements = jokesData.map(joke => {
        // {joke.setup} 跟 setup在 jokesData 保持一致
        return <Joke setup={joke.setup} punchline={props.punchline} />
    })
    return (
        <div>
            {jokeElements}
        </div>
    )
}