PROGRAMING/React

[REACT] Dog Picture - API

donghunl 2024. 3. 6. 09:29
반응형

Use a dog picture API to display dog images on React.

// Using API: https://dog.ceo/dog-api/

Link to an API in a comment which you will use to fetch a random dog picture.

 

DogPIcs.js

import { useEffect, useState } from "react"

const getDogPic = async () => {
  const response = await fetch('https://dog.ceo/api/breeds/image/random')
  const dog = await response.json()
  return dog.message
}
export default function DogPics() {
  // API: https://dog.ceo/dog-api/
  const [dogPic, setDogPic] = useState('')
  useEffect(() => {
    getDogPic().then(pic => setDogPic(pic))
  }, [])
  return (
    <div className='dog-pics'>
      <img src={dogPic} />
      <button onClick={async e => setDogPic(await getDogPic())}>🐶</button>
    </div>
  )
}

 

App.js

import DogPic from './DogPics'

function App () {
  return (
    <div className='App'>
      <DogPic />
    </div>
  )
}

export default App

 

index.js

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';

ReactDOM.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>,
  document.getElementById('root')
);

// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals();

 

index.css

html, body {
  font-family: sans-serif;
}

.page {
  height: 100vh;
  width: 100vw;
  display: flex;
  align-items: center;
  justify-content: center;
}

.dog-pics {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  margin-top: 50px;
}

 

결과 화면

반응형