React Dropdown Component with Infinite Scrolling and API Data Loading
To implement a React dropdown component that calls an API and appends data to the dropdown when scrolled to the end, you can follow the steps below:
\
- Install the necessary dependencies:\
npm install axios react-infinite-scroll-component\
```\
\
2. Create a new component called `Dropdown` and import the necessary modules:\
```jsx\
import React, { useState, useEffect } from 'react';\
import axios from 'axios';\
import InfiniteScroll from 'react-infinite-scroll-component';\
```\
\
3. Create the `Dropdown` component and define the initial state:\
```jsx\
const Dropdown = () => {\
const [data, setData] = useState([]);\
const [page, setPage] = useState(1);\
const [hasMore, setHasMore] = useState(true);\
\
useEffect(() => {\
fetchData();\
}, []);\
\
const fetchData = async () => {\
try {\
const response = await axios.get(`YOUR_API_ENDPOINT?page=${page}`);\
const newData = response.data;\
setData(prevData => [...prevData, ...newData]);\
setPage(prevPage => prevPage + 1);\
setHasMore(newData.length > 0);\
} catch (error) {\
console.error(error);\
}\
};\
\
return (\
<InfiniteScroll\
dataLength={data.length}\
next={fetchData}\
hasMore={hasMore}\
loader={<h4>Loading...</h4>}\
endMessage={<p>No more items to load.</p>}\
>\
<select>\
{data.map(item => (\
<option key={item.id} value={item.id}>\
{item.name}\
</option>\
))}\
</select>\
</InfiniteScroll>\
);\
};\
\
export default Dropdown;\
```\
\
4. Replace `YOUR_API_ENDPOINT` with the actual API endpoint you want to call. Adjust the response handling logic based on your API's response structure.\
\
5. Use the `Dropdown` component in your main component or any other component:\
```jsx\
import React from 'react';\
import Dropdown from './Dropdown';\
\
const App = () => {\
return (\
<div>\
<h1>Scrollable Dropdown</h1>\
<Dropdown />\
</div>\
);\
};\
\
export default App;\
```\
\
With this setup, the `Dropdown` component will call the API and append data to the dropdown each time it is scrolled to the end. The `InfiniteScroll` component from `react-infinite-scroll-component` handles the scrolling behavior and triggers the `fetchData` function when needed.
原文地址: https://www.cveoy.top/t/topic/pq4m 著作权归作者所有。请勿转载和采集!