Answer the question
In order to leave comments, you need to log in
How to combine search and pagination in React?
Good afternoon, there are 2 components, one is responsible for pagination, the other for search, as a result, only one of the two can work humanly, if pagination works, then the search does not work and vice versa, I imagine that they need to be combined into one component and done only one get request and accordingly there are already slices, filters and everything else, but I absolutely don’t understand how to do it, can someone tell me, thanks, here is the
Pagination code:
function Paginate() {
const [offset, setOffset] = useState(0);
const [data, setData] = useState([]);
const [perPage] = useState(5);
const [pageCount, setPageCount] = useState(0)
const getData = async() => {
const res = await axios.get('http://localhost:5000/business')
const data = res.data;
const slice = data.slice(offset, offset + perPage)
const postData = slice.map((item) => (
<Item key={item.id} {...item} />
))
setData(postData)
setPageCount(Math.ceil(data.length / perPage))
}
const handlePageClick = (e) => {
const selectedPage = e.selected;
setOffset(selectedPage * perPage)
};
useEffect(() => {
getData()
}, [offset])
return (
<div className="App">
{data}
<ReactPaginate
previousLabel={"prev"}
nextLabel={"next"}
breakLabel={"..."}
breakClassName={"break-me"}
pageCount={pageCount}
marginPagesDisplayed={2}
pageRangeDisplayed={5}
onPageChange={handlePageClick}
containerClassName={"pagination"}
subContainerClassName={"pages pagination"}
activeClassName={"active"}/>
</div>
);
}
export default Paginate;
import React, {useState, useEffect} from 'react'
import axios from 'axios'
import Item from './Player.js';
import './Search.scss';
import Paginate from './Paginate.js';
const SearchBar = () => {
const [business, setBusiness] = useState([]);
const [value, setValue] = useState('');
const getBusiness = () => {
axios.get('http://localhost:5000/business')
.then((response) => {
setBusiness(response.data)
})
}
useEffect(() => {
getBusiness()
}, [])
const filtered = business.filter(item => {
return item.player_name.toLowerCase().includes(value.toLowerCase())
})
return (
<>
<div className="form">
<form className="search_form">
<input
type="text"
placeholder="Players"
onChange={(event) => setValue(event.target.value)}
/>
</form>
</div>
<div className="players">
<Paginate />
{/* {
filtered.map((item, index, ) => {
return (
<Item item={item} key={index} />
)
})
} */}
</div>
</>
);
};
export default SearchBar;
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question