Trying to automatically increment the index of my switch statement so my site will automatically switch different elements out.
Trying to achieve this using:
export default function MainComponent(props) {
let index = 0;
switch (index) {
case 0:
counter++;
console.log(index)
return (
//ELEMENT 1
);
case 1:
index++;
console.log(index)
return (
//ELEMENT 2
);
case 2:
index++;
console.log(index)
return (
ELEMENT 3
);
case 3:
index++;
console.log(index)
return (
//ELEMENT 4
);
default:
return (
null
)
I can see that the index increments in the console so I don't understand why my switch state isn't switching to the next element.
Any help appreciated
If I understand you correctly you need to use hooks for the state. Otherwise, React won't rerender your component.
import { useCallback, useState } from "react";
export default function App() {
let [index, setIndex] = useState(0)
let increment = useCallback(() => {
setIndex(index => index + 1);
}, [setIndex])
switch (index) {
case 0:
increment()
console.log(index)
return 1
case 1:
increment()
console.log(index)
return 2
case 2:
increment()
console.log(index)
return 3
case 3:
increment()
console.log(index)
return 4
default:
return 'default'
}
}
But renders happen quickly. You will need some timeouts to see different cases on the screen