Hey I have a small problem, I have something like slide show app and I want to change the component to another one when we finish all slides on the first one.
import { useState } from 'react';
const text = [
"Text1",
"Text2",
"Text3",
"Text4",
"Text5"
]
export function Intro() {
let [index, setIndex] = useState(0)
const handleIndexIncrease = () => {
if (index == text.length - 1){
return <Test/>;
} else {
setIndex(index + 1)
}
}
return (
<>
<div className="mainContainer">
<h1>{text[index]}</h1>
<button id='btn' onClick={handleIndexIncrease}>🠖</button>
</div>
</>
)
}
function Test() {
return (
<>
<div className="mainContainer">
<h1>Component2</h1>
</div>
</>
)
}
I have 5 texts and a button that change it to another one, when all the textes finishes I want to render Test() component (so when index === text.length – 1). I know that if (index == text.length - 1){ return <Test/>; } doesnt rerender anything so it wont show but I dont know how to write it well
I have tried state sharing
export function Intro() {
let [index, setIndex] = useState(0)
const handleIndexIncrease = () => {
if (index == text.length - 1){
return <Test isActive={index == text.length - 1}/>;
} else {
setIndex(index + 1)
}
}
return (
<>
<div className="mainContainer">
<h1>{text[index]}</h1>
<button id='btn' onClick={handleIndexIncrease}>🠖</button>
</div>
</>
)
}
function Test({isActive}) {
if(isActive === 1) {
return (
<>
<div className="mainContainer">
<h1>ESA</h1>
</div>
</>
)
}
}
but it still doesnt rerender anything
>Solution :
Please change your code like this :
import { useState } from 'react';
const text = [
"Text1",
"Text2",
"Text3",
"Text4",
"Text5"
]
export default function Test3() {
let [index, setIndex] = useState(0)
const handleIndexIncrease = () => {
if (index == text.length ) {
// console.log('here!')
// return <Test/>;
} else {
setIndex(index + 1)
}
}
return (
<>
<div className="mainContainer">
<h1>{index == text.length ? <Test /> : text[index]}</h1>
<button id='btn' onClick={handleIndexIncrease}>🠖</button>
</div>
</>
)
}
function Test() {
return (
<>
<div className="mainContainer">
<h1>Component2</h1>
</div>
</>
)
}
I am not sure that if I understood your goal.
But it will works correctly to change the component.
Or do you want to hide button when you finish changing?
If your answer is yes, please use this code
<button id='btn' onClick={handleIndexIncrease} hidden = {index == text.length}>🠖</button>