I'm working on a React.js pagination and I would like to set an active class whenever I press a specific number.
How can I add this in the below code:
function Pagination() {
const [page, setPage] = useState(1);
const goPreviousPage = () => {
if (page > 1) {
setPage(prevPage => prevPage - 1);
}
};
const goNextPage = () => {
if (page < 11) {
setPage(prevPage => prevPage + 1);
}
};
const goSpecificPage = page => {
setPage(page);
};
return (
<div className="pagination-wrapper">
<button onClick={goPreviousPage} disabled={page <= 1}>
Previous Page
</button>
<button className="" onClick={() => goSpecificPage(page)}>{page}</button>
<button onClick={() => goSpecificPage(page + 1)}>{page + 1}</button>
<button onClick={() => goSpecificPage(page + 2)}>{page + 2}</button>
<button onClick={goNextPage} disabled={page >= 10 }>
Next Page
</button>
</div>
);
}
Many thanks!
You need to keep track of currently active button within your state and assign className
conditionally:
const { useState } = React, { render } = ReactDOM, rootNode = document.getElementById('root') const PaginationButtons = () => { const [activeButton, setActiveButton] = useState(1), handleButtonClick = buttonIdx => { setActiveButton(buttonIdx) // do whatever you need upon button click } return ( <div> <button onClick={() => handleButtonClick(0)}>Prev</button> <button onClick={() => handleButtonClick(1)} className={activeButton == 1? 'active': ''} > 1 </button> <button onClick={() => handleButtonClick(2)} className={activeButton == 2? 'active': ''} > 2 </button> <button onClick={() => handleButtonClick(3)} className={activeButton == 3? 'active': ''} > 3 </button> <button onClick={() => handleButtonClick(4)}>Next</button> </div> ) } render ( <PaginationButtons />, rootNode )
.active { background-color: orange; color: #fff; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.12.0/umd/react.production.min.js"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.11.0/umd/react-dom.production.min.js"></script><div id="root"></div>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.