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:

  1. Install the necessary dependencies:
npm install axios react-infinite-scroll-component
  1. Create a new component called Dropdown and import the necessary modules:
import React, { useState, useEffect } from 'react';
import axios from 'axios';
import InfiniteScroll from 'react-infinite-scroll-component';
  1. Create the Dropdown component 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;
  1. 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.

  2. Use the Dropdown component 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

react dropdown component when scroll to the end call api and append data to the dropdown

原文地址: https://www.cveoy.top/t/topic/hHZD 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录