Skip to content

Instantly share code, notes, and snippets.

@jc-k91
Forked from brendanquirk/hooks2.md
Last active July 16, 2021 14:41
Show Gist options
  • Save jc-k91/dd3c185763b21694d69517bafeb243bc to your computer and use it in GitHub Desktop.
Save jc-k91/dd3c185763b21694d69517bafeb243bc to your computer and use it in GitHub Desktop.

Intermediate React

Setup

  • npx create-react-app intermediate-react
  • Delete all starter code in App.js
  • npm start to get the app running

Basic App.js Setup

import React, { useState } from 'react'

const App = () => {
  return (
    <div>
      <h1>App</h1>
    </div>
  )
}

export default App

Map over state to create multiple elements

  • Lets dynamically create multiple elements based on our state which we will just set as an array of items for now.
  • Basic map syntax:
somearray.map((element) => {
  return something
})
  • Lets add state to our component so we have something to map over:
let [items, setItems] = useState(['ketchup', 'icecream', 'soda'])
  • Then lets map over that array to create an unordered list inside of our return statement:
<ul>
  {items.map((item) => {
    return <li>{item}</li>
  })}
</ul>

Ternary Operators

  • Quick review of ternary operators:
const name = 'brendan'
//if name is 'brendan' result = 'Name is brendan' else result = 'Name is not brendan'
const result = name === 'brendan' ? 'Name is brendan' : 'Name is not brendan'
console.log(result)
  • Lets incorporate ternary operators into our code. First lets add a piece of state to use as our conditional in the ternary:
let [inStock, setInStock] = useState(true)
  • Next lets adjust our map a bit so that if inStock is true we will have some in stock text if not some out of stock text:
{items.map((item) => {
  return (
    <div>
      {inStock ? (
        <li>In Stock: {item}</li>
      ) : (
        <li>Out of Stock: {item}</li>
      )}
    </div>
  )
})}

AJAX and React

  • Lets start with a barebones React App for our AJAX example.
  • We're going to be using an npm package called axios to make all of our requests within react, lets run npm i axios and then in App.js under where we pull in react lets add:
import axios from 'axios'
  • Next we're going to need another hook called useEffect, which will only run once when the application loads.
import React, { useState, useEffect } from 'react'
  • Now we can make our axios request:
const getActivity = () => {
  axios.get('https://www.boredapi.com/api/activity').then((response) => {
    setActivity(response.data.activity)
  })
}

// passing an empty array as the second argument will prevent an infinite loop by mounting and then unmounting after it has run once
useEffect(() => {
  getActivity()
}, [])
  • Lets render an activity:
return (
  <div>
    <h1>{activity}</h1>
  </div>
)
  • Just for fun lets add a button that we can click to get a new random activity:
return (
  <div>
    <h1>{activity}</h1>
    <button onClick={getActivity}>Get new activity</button>
  </div>
)

Multiple Components with Props

  • Sometimes our applications will get too big to keep everything in one component, lets refactor our app so that we can have two components.
  • First lets mkdir src/components
  • Then touch src/components/Activity.js
  • Lets move our h1 to the new Activity component:
import React from 'react'

const Activity = (props) => {
  return (
    <div>
      <h1>{props.activity}</h1>
    </div>
  )
}

export default Activity
  • Next we need to import our Activity component into our App componet:
import Activity from './components/Activity'
  • Lastly lets render the Activity component and pass activity as a prop into the Activity component:
return (
  <div>
    <Activity activity={activity} />
    <button onClick={getActivity}>Get new activity</button>
  </div>
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment