'Next and Back button functionality not working?
I have three pages to be displayed by the click of next and back button and by default first page would be shown (ExternalDamage ) and clicking on NEXT the second page would be shown and BACK button would take to the last page, but its not updating the state ? I need to use state to update the count of the array index but its not updating the index
/* eslint-disable consistent-return */
import React, { useState } from 'react';
// import classnames from 'classnames';
import ScreenDamage from './ScreenDamage';
import Battery from './Battery';
import ExternalDamage from './ExternalDamage';
import Footer from './Footer';
import styles from './manualCheck.module.scss';
import VerticalSpacing from '../../core/VerticalSpacing/VerticalSpacing';
// import AdditionalChecks from './AdditionalChecks'
const ManualCheck = () => {
const [index, setIndex] = useState(0);
const item = [
<ExternalDamage />,
<ScreenDamage />,
<Battery />,
];
const handleBackButton = () => {
if (index !== 0) {
setIndex(index - 1);
console.log(index);
}
};
const handleNextButton = () => {
setIndex(index + 1);
console.log(index);
};
return (
<div>
{item[index]}
<div className={styles.footer}>
<VerticalSpacing size={ABLE_SPACING_SIZE.spacing2x} />
{/* eslint-disable jsx-a11y/anchor-is-valid */}
<a
href="#"
onClick={() => handleBackButton()}
>
Back
</a>
{/* eslint-enable jsx-a11y/anchor-is-valid */}
{/* eslint-disable jsx-a11y/anchor-is-valid */}
<a
href="#"
onClick={() => handleNextButton()}
>
Next
</a>
{/* eslint-enable jsx-a11y/anchor-is-valid */}
</div>
<VerticalSpacing size={ABLE_SPACING_SIZE.spacing15x} />
</div>
);
};
export default ManualCheck;
Solution 1:[1]
You need to add a e.preventDefault() in the handleBackButton() and handleNextButton() as such :
const handleBackButton = (e) => {
e.preventDefault();
if (index !== 0) {
setIndex(index - 1);
console.log(index);
}
};
const handleNextButton = (e) => {
e.preventDefault();
setIndex(index + 1);
console.log(index);
};
The following link might help you in your quest :
Solution 2:[2]
Well your code can be improved as followings:
First, you are not passing any argument to the functions so you should use onClick as followings:
<a
href="#"
onClick={handleBackButton}>
Back
</a>
<a href="#"
onClick={handleNextButton}
>
Next
</a>
Also your state is dependent on the previous state. So, to ensure that you are getting the latest snapshots, you must update your state as below:
const handleBackButton = (e) => {
e.preventDefault();
if (index !== 0) {
setIndex(prevIndex => prevIndex - 1);
console.log(index);
}
};
const handleNextButton = (e) => {
e.preventDefault();
setIndex(prevIndex => prevIndex + 1);
console.log(index);
};
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | dorianDevTech |
| Solution 2 |
