20줄의 코드로 React에서 아름다운 로딩 알림을 만드세요!
16281 단어 javascriptproductivityreactwebdev
아이디어
솔직히 말해서 브라우저의 JavaScript 경고는 형편없습니다! 저는 알림과 토스트를 반응형으로 쉽게 만들 수 있는 완벽한 라이브러리를 찾으려고 노력했고 여기에서 제가 알아낸 것이 있습니다 😀
도서관
토스트를 만들기 위한 일부 반응 구성 요소 라이브러리를 찾을 수 있었지만 내가 찾은 가장 구현하기 쉽고 가장 깨끗한 라이브러리는 react-hot-toast , 경고: It's too hot!
토스트 만들기
라이브러리 사용은 매우 쉽고 문서 페이지에서 확인할 수 있는 다양한 토스트가 있지만 이 블로그에서는 API에서 데이터를 가져올 때 로드 알림을 생성하는 약속 토스트에 중점을 둘 것입니다. .
반응 프로젝트를 생성하여 시작하겠습니다.
예제 앱에 설치한 종속성:
API에서 데이터를 가져오는 부분으로 빠르게 이동하겠습니다. 내 Spotify 데이터를 가져오는 API가 있고 여기에서 사용할 것입니다.
내
app.jsx
파일:import { useState } from 'react'
import toast, { Toaster } from 'react-hot-toast';
function App() {
const [data, setData] = useState(null)
function fetchData() {
return fetch('https://spotify-np-api.vercel.app/api').then(
(response) => {
return response.json();
}
).then(
(data) => {
return data;
}
).catch(
(error) => {
console.error(error);
}
)
}
const getToast = () => {
toast.promise(fetchData(), {
loading: 'getting song data...',
success: (data) => {
setData(data)
return 'fetched top song data'
},
error: "couldn't fetch data!",
})
}
return (
<div className="relative App flex justify-center items-center bg-red-200 w-screen h-screen flex-col gap-3 p-3">
<button onClick={getToast} className='hover:rotate-3 duration-300 bg-red-400 -rotate-3 shadow-xl rounded-md px-6 py-2 text-rose-100 font-bolder' >🎵ㅤGet Song Data</button>
{data &&
<div className='hover:-rotate-1 duration-300 cursor-pointer bg-red-400 flex flex-col rotate-1 justify-center items-center h-1/4 w-full lg:w-1/3 md:w-1/2 shadow-2xl rounded-md p-4'>
<h1 className='text-center text-2xl mb-3 text-red-100 font-bold'>ashish's top song for this week 🎵</h1>
<h1 className='text-center text-xl font-bolder text-rose-100'>{data.top.song.toLowerCase()}</h1>
<h1 className='text-center text-md font-bolder text-rose-200'>~ {data.top.artist}</h1>
</div>
}
<h2 className='text-red-600 text-sm absolute bottom-0 text-center p-4'>made by ashish using react-hot-toast</h2>
<Toaster
toastOptions={{
className: '',
style: {
background: '#f87171',
color: '#ffe4e6',
}
}}
/>
</div>
)
}
export default App
이제 분해합시다.
약속을 가져오고 반환하는 함수, 토스트 메서드에서 사용할 약속을 반환합니다.
...
function fetchData() {
return fetch('https://spotify-np-api.vercel.app/api').then(
(response) => {
return response.json();
}
).then(
(data) => {
return data;
}
).catch(
(error) => {
console.error(error);
}
)
}
...
이제 react-hot-toast를 구현해 봅시다! 우선 파일에서 가져와야 합니다.
import toast, { Toaster } from 'react-hot-toast';
...
OnClick
함수를 사용하여 toast.promise()
를 사용하는 경우 toast.promise()
메서드에서 약속을 전달해야 하며 두 번째 인수는 약속 상태를 기반으로 토스트가 표시해야 하는 메시지를 정의하는 개체msgs
입니다. 여기에서도 상태를 설정하고 데이터를 변경하는 기능을 사용할 수 있습니다. 약속을 성공적으로 가져온 경우 앱에 표시할 데이터를 업데이트하기 위해 setData()
를 사용했습니다....
const getToast = () => {
toast.promise(fetchData(), {
loading: 'getting song data...',
success: (data) => {
setData(data)
return 'fetched top song data'
},
error: "couldn't fetch data!",
})
}
...
알림을 렌더링하려면 앱 끝에
<Toaster />
구성 요소를 추가해야 합니다. 여기에서 전달된 ToastOptions
개체를 사용하여 알림의 스타일을 지정할 수 있습니다....
<Toaster
toastOptions={{
className: '',
style: {
background: '#f87171',
color: '#ffe4e6',
}
}}
/>
...
이제 가져온 데이터를 표시하는 div 구성 요소를 만들어 보겠습니다.
...
{data &&
<div className='hover:-rotate-1 duration-300 cursor-pointer bg-red-400 flex flex-col rotate-1 justify-center items-center h-1/4 w-full lg:w-1/3 md:w-1/2 shadow-2xl rounded-md p-4'>
<h1 className='text-center text-2xl mb-3 text-red-100 font-bold'>ashish's top song for this week 🎵</h1>
<h1 className='text-center text-xl font-bolder text-rose-100'>{data.top.song.toLowerCase()}</h1>
<h1 className='text-center text-md font-bolder text-rose-200'>~ {data.top.artist}</h1>
</div>
}
...
그리고 이것으로 우리는 API에서 데이터를 가져와 아름다운 건배와 함께 보여주는 간단한 앱을 성공적으로 만들었습니다. 최종 앱은 다음과 같습니다.

여기까지 읽어주셔서 감사합니다. 질문이나 댓글로 물어보고 싶은 것이 있으면 최대한 빨리 답변해 드리겠습니다. :)
Source Code
Reference
이 문제에 관하여(20줄의 코드로 React에서 아름다운 로딩 알림을 만드세요!), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://dev.to/asheeshh/create-beautiful-loading-notification-in-react-in-20-lines-of-code-3cen텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념
(Collection and Share based on the CC Protocol.)