I am getting an error as Uncaught Error: Cannot add node 1 because a node with that id is already in the Store. while try to use the function.
here is my function:
import { useEffect, useState } from "react";
import "./styles.css";
export default function App() {
const [value, setValue] = useState(0);
const slides = ["one", "two", "thre"];
let size = slides.length;
useEffect(() => {
setValue(size);
}, [size]);
const prev = () => {
if (size && size < 1 && size && size > slides.length) return;
size--;
};
const next = () => {
if (size && size < 1 && size && size > slides.length) return;
size++;
};
return (
<div className="slider">
<a href="/" className="prev" onClick={prev}>
Previous
</a>
<h2>Barking Road, London {value}</h2>
<a href="/" className="next" onClick={next}>
Next
</a>
</div>
);
}
I want to allow the user to click until 1 as min and 3 as max. but it not works.
LiveDemo
useEffect to achieve that, also change your <a> tag to a <button>Working snippet:
function App() {
const [value, setValue] = React.useState(1);
const slides = ["one", "two", "thre"];
const prev = () => {
if (value > 1) setValue(value - 1);
};
const next = () => {
if (value < slides.length) setValue(value + 1);
};
return (
<div className="slider">
<button className="prev" onClick={prev}>
Previous
</button>
<h2>Barking Road, London {value}</h2>
<button className="next" onClick={next}>
Next
</button>
</div>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.production.min.js"></script>
<div id="root"></div>
Just update like this:
const prev = () => {
if (value <= 1) return;
setValue(value - 1);
};
const next = () => {
if (value >= slides.length) return;
setValue(value + 1);
};
And change tag by other tag: https://codesandbox.io/s/stupefied-robinson-yjmkm?file=/src/App.tsx
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With