I have a Modal component that receives a data set of image sources and the initial index. Each side of the Modal has navigation arrows that either increment or decrement the current index. This is a simplified version of the Modal component:
function Modal({ index, data, onClose, show }) {
const [currIndex, setCurrIndex] = useState(index);
return (
<main className={show ? "Modal Open" : "Modal"}>
<img src={data[currIndex].link} alt="ModalImage" />
<IconContext.Provider value={{ className: "Arrows" }} >
{currIndex < data.length - 1 && (<AiOutlineRight className="ArrowNext" onClick={() => setCurrIndex(currIndex + 1)} />)}
{currIndex > 0 && (<AiOutlineLeft className="ArrowLast" onClick={setCurrIndex(currIndex - 1)} />)}
</IconContext.Provider>
<div className="ModalBackground" onClick={onClose} />
</main>
}
export default Modal;
I am using it like so:
<Modal show={show} onClose={() => setShow(false)} data={filterData()} index={modalIndex} ></Modal>
This must be bad practice because it is not working. The state is initially always 0 and never updates when I increment or decrement it. It gets immediately reset to 0. The state is stuck at 0. The props value is being passed correctly and everything else just won't work as the initial state. Is there another way I can set the initial state in the Modal based on the selection in another component?