react dropdown component when scroll to the end call api and append data to the dropdown
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
- Create a new component called
Dropdownand import the necessary modules:
import React, { useState, useEffect } from 'react';
import axios from 'axios';
import InfiniteScroll from 'react-infinite-scroll-component';
- Create the
Dropdowncomponent and define the initial state:
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;
-
Replace
YOUR_API_ENDPOINTwith the actual API endpoint you want to call. Adjust the response handling logic based on your API's response structure. -
Use the
Dropdowncomponent in your main component or any other component:
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/hHZD 著作权归作者所有。请勿转载和采集!