Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Click Text and Change Text React

I have a question about onClick event using React hooks. I actually want the text to change to another text when user click and when user click again, it goes back to first text. For example user click text "Change First", then the text change to "Change Second". Then if user click the "Change Second", the text change to "Change First". It will change as long as user click the text.

This is my useState function:

const [shopStat, setshopChange] = useState("Change first");

And below is the part where I want to change the text:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

<div className="featuredItem">
  <span className="featuredTitle">Your text is</span>
     <div className="featuredMoneyContainer">
        <span
         className="featuredMoney"
         style={{ color: green }}
         onClick={() => setshopChange("Change second")}
         >
         {shopStat}
         </span>
     </div>
</div>

However, the code above only change the text once to "Change Second" and I cannot click the text again to change it back to "Change First". Hope you all can help me. Thank you.

>Solution :

Set state functions accept curent state as parameter so you can use it like that.

onClick={() => setshopChange((currentState) =>  currentState === "Change second"  ? "Change First" : "Change second"  )}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading