How do I change the text and button text back to its original state with an onClick? I know theres a setTimeout but I only want the change to revert back FOR BOTH the button and text when I click on it. Currently I can only use it one way. If i click on it, it changes from Original to new but I will like to change back to Original if i click on it again. Thanks!
Code:
import React, {useState} from 'react'
const Card = () => {
const[text, setText] =useState('original')
const [buttonText, setButtonText] = useState("Original");
return (
<div className='translate uppercase py-5 break-normal text-center mx-4 space-y-2 font-bold'>
<div className="App">
<button className='rounded-full border-black border-solid'
type="submit"
onClick={() => {
setButtonText("New");
setText('New')
}}
>
{buttonText}
</button>
</div>
<h2>{text}</h2>
</div>
)
}
export default Card;
CodePudding user response:
If you Know both values you can use this solution
import React, {useState} from 'react'
const Card = () => {
const [captions, setCaptions] = useState([
{ buttonText: "orginal", text: "orginal" },
{ buttonText: "new", text: "new" }
]);
const[flag, setFlag] =useState(0)
return (
<div className='translate uppercase py-5 break-normal text-center mx-4 space-y-2 font-bold'>
<div className="App">
<button className='rounded-full border-black border-solid'
type="submit"
onClick={() => {
setCaptions(captions);
setFlag(flag === 0 ? 1 : 0);
}}
>
{captions[flag].buttonText}
</button>
</div>
<h2>{captions[flag].text}</h2>
</div>
)
}
export default Card;
If you don't know new value you can add to captions new value
CodePudding user response:
Try this:
const [isOriginal, setIsOriginal] = useState(true)
onClick={() => {
if(isOriginal) {
setButtonText("New");
setText('New')
setIsOriginal(false)
} else if (!isOriginal) {
setButtonText("Original");
setText('original')
setIsOriginal(true)
}
}
By checking the original state, you can conditionally set text values.