You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
constname='brendan'//if name is 'brendan' result = 'Name is brendan' else result = 'Name is not brendan'constresult=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:
importaxiosfrom'axios'
Next we're going to need another hook called useEffect, which will only run once when the application loads.
importReact,{useState,useEffect}from'react'
Now we can make our axios request:
constgetActivity=()=>{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 onceuseEffect(()=>{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><buttononClick={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.