Previous and Next Buttons in React JS
Here’s an example of how you can create previous and next buttons in React JS:
{`
import React, { useState } from 'react';
const App = () => {
const [currentIndex, setCurrentIndex] = useState(0);
const data = ['Item 1', 'Item 2', 'Item 3', 'Item 4', 'Item 5'];
const handlePrevious = () => {
setCurrentIndex((prevIndex) => (prevIndex > 0 ? prevIndex - 1 : 0));
};
const handleNext = () => {
setCurrentIndex((prevIndex) => (prevIndex < data.length - 1 ? prevIndex + 1 : prevIndex));
};
return (
{data[currentIndex]}
);
};
export default App;
`}
In the above example, we use the useState hook to initialize a currentIndex state variable with an initial value of 0. The data array holds the items to be displayed.
The handlePrevious function is called when the “Previous” button is clicked. It checks if the current index is greater than 0, and if so, decrements the index by 1. Otherwise, it stays at 0 to prevent going below the first item.
The handleNext function is called when the “Next” button is clicked. It checks if the current index is less than the length of the data array minus 1, and if so, increments the index by 1. Otherwise, it stays at the last index to prevent going beyond the last item.
The h3 element displays the current item based on the current index.
The “Previous” button is disabled when the current index is 0, indicating the first item is currently being displayed. Similarly, the “Next” button is disabled when the current index is at the last index of the data array, indicating the last item is currently being displayed.