DEV Community

Sowntharya
Sowntharya

Posted on

React in Action: State, Events, Inputs & Forms

1. Counter Program

import { useState } from "react";

function Counter(){
    // let i=0;
    // return(
    //     <div>
    //     <h1>Count : {i} </h1>
    //     <button onClick= {increament}></button>
    //     </div>
    // )
    console.log("component ReRendered....");
    // let cout = 0
    const [count, setCount] = useState(0);

    function increment(){
        // count++
        // console.log(count)
        setCount(count + 1);
        //setCount(500);

    }

    function decrement() {
        if(count>0){

        setCount(count - 1)
    }
}

    function reset() {

        setCount(0);   
    }

    return(
        <div>
            <h1>Count : {count} </h1>
            <button onClick= {increment}>+</button>
             <button onClick= {decrement}>-</button>
              <button onClick= {reset}>reset</button>
        </div>
    )
}

export default Counter;
Enter fullscreen mode Exit fullscreen mode

To call your components inside App.jsx using tags like

import Counter from './Counter';

function App() {
  return (
    <div>
      <Counter />
    </div>
  );
}

export default App;
Enter fullscreen mode Exit fullscreen mode

2. InputField

import { useState } from "react";

function InputField() {
  const [name, setName] = useState("");

  return (
    <div>
      <h2>Enter Your Name</h2>

      <input
        type="text" placeholder="Enter your name" value={name} onChange={(e) => setName(e.target.value)} />

        <h3>Hello, {name}</h3>

           {/* {name.trim() && <h3>Hello, {name}</h3>} */}

    </div>
  );
}

export default InputField;
Enter fullscreen mode Exit fullscreen mode

*3.Show/ Hide Text *

import { useState } from "react";

function ShowHideText() {
  const [show, setShow] = useState(false);

  return (
    <div>
      <h2>Show / Hide Text</h2>

      <button onClick={() => setShow(!show)}>
        {show ? "Hide Text" : "Show Text"}
      </button>

      {show && (
        <p>
          Hello! Welcome to React.
          You are learning conditional rendering.
        </p>
      )}
    </div>
  );
}

export default ShowHideText;
Enter fullscreen mode Exit fullscreen mode

To call your components inside App.jsx using tags like

import Showhide from './Showhide';

function App() {
  return (
    <div>
      <Showhide />
    </div>
  );
}

export default App;
Enter fullscreen mode Exit fullscreen mode

Top comments (0)