In this tutorial we are going to learn about how to toggle data using onclick events and useState hook to change the state.
| import "./styles.css"; import React, { useState } from "react";   export default function App() {  const [count, setCount] = useState("mern stack developer");    const change = () => {    let val = count;      if (val === "mern stack developer") {      setCount("tejas talkar");    } else {      setCount("mern stack developer");    }  };  return (    <div className="App">      <p>{count} </p>      <button onClick={change}>click me</button>    </div>  ); } | 
Here we define the initial state using the useState. Where Count is the initial state and setCount is the updated state.   
| const [count, setCount] = useState("mern stack developer"); | 
Here we define function change, here we use the user initial state that is count.and toggle data using if and else statements.
|  const change = () => {    let val = count;    if (val === "mern stack developer") {      setCount("tejas talkar");    } else {      setCount("mern stack developer");    }  }; | 
Here is a jsx code here we can finally print the count and add a button and give the event onClck by passing function change 
| return (    <div className="App">      <p>{count} </p>      <button onClick={change}>click me</button>    </div>  ); } | 
output:-
code link
 
0 Comments