DEV Community

VINOTH
VINOTH

Posted on

React useState Hook - Day1

1) Toggle Button:
You build a button that switches between:
"ON" ↔ "OFF"
What type of state should you use?
What is the best initial value?

import { useState } from "react"

function Toggle() {

  const [status, setStatus] = useState("OFF");

    function togglebtn() {

            if (status === "OFF") {
                setStatus("ON");
            }else{
                setStatus("OFF");
            }
    }

    return(
        <div>
            <h1>{status}</h1>
            <button onClick={togglebtn}>Toggle</button>
        </div>
    )
}

export default Toggle

Enter fullscreen mode Exit fullscreen mode

2) Input Field Value:
You have a text input.
User types name and you want to display:
Hello, Vinoth
Why must the input value be stored in useState?
What happens if you use a normal variable?

import { useState } from "react"

function Name() {

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

    function handle(e) {

        setName(e.target.value);

    }

    return(
        <div>
            <input 

                 value={name}
                 onChange={handle}
            />
            <h1>Hello, {name}</h1>
        </div>
    )
}

export default Name
Enter fullscreen mode Exit fullscreen mode

3) Show/Hide Text:
You want to show paragraph only when button is clicked.
What kind of state works best?
Why boolean is suitable here?

import { useState } from "react"

function Text() {

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

    function handle () {

        if (show === false) {
            setShow(true)
        }else{
            setShow(false)
        }

    }

    return(
        <div>
           <button onClick={handle}>
            show / hide
           </button>

           {show && <p>Hello! This is my paragraph.</p>}
        </div>
    )
}

export default Text

Enter fullscreen mode Exit fullscreen mode

4) Character Counter:
User types in textarea. You show number of characters.
How do you track text length?
Should you store both text and length in state?

import { useState } from "react"

function Count() {

  const [text, setText]= useState("");



    return(
        <div>
          <textarea 

          value={text}
          onChange={(e)=>setText(e.target.value)}

          />

          <p>Characters: {text.length}</p>
        </div>
    )
}

export default Count
Enter fullscreen mode Exit fullscreen mode

5) Form with Multiple Inputs
You have 5 input fields (name, email, phone, city, password).
Better to use:
5 separate useState?
OR one object state?
Why?
What problem happens if you update object state incorrectly?

import { useState } from "react";

function FormHandling() {


 const [form, setForm] = useState({
name: "",
email:"",
phone:"",
city:"",
password:""
})

function handle(e) {
    setForm({...form, [e.target.name]: e.target.value })
    console.log(e.target.value);

}


    return(
        <div>

            <form >

                <label htmlFor="name">name</label>
                <input type="text" id="name" name = "name" onChange={handle}/>

                <label htmlFor="email">email</label>
                <input type="email" id="email" name="email" onChange={handle}/>

                <label htmlFor="phone">phone</label>
                <input type="phone" id="phone" name="phone" onChange={handle}/>

                <label htmlFor="city">city</label>
                <input type="city" id="city" name="city" onChange={handle}/>

                <label htmlFor="password">pass</label>
                <input type="password" id="password" name="password" onChange={handle}/>

            </form>
            <h1>{`Name: ${form.name}, Email: ${form.email}, phone: ${form.phone}, city: ${form.city} ,password: ${form.password}`}</h1>

        </div>
    )
}

export default FormHandling;
Enter fullscreen mode Exit fullscreen mode

6) Checkbox Selection List
User can select multiple skills:
☐ React
☐ Node
☐ Java
☐ SQL
What should be the state type?
How will you add/remove values from state array?

import { useState } from "react"

function Checkbox() {

    const [skills, setSkills] = useState([])

    function handle(e) {


        if (e.target.checked) {
            setSkills([...skills, e.target.value])
        } else {
            // skills.filter((skill) => e.target.value != skill)
            setSkills(
                skills.filter((skill) => skill !== e.target.value)
            );
        }
    }

    return (
        <div>

            <input type="checkbox" value={"sql"} onChange={handle} />sql <br />
            <input type="checkbox" value={"java"} onChange={handle} /> java  <br />
            <input type="checkbox" value={"node"} onChange={handle} /> node  <br />
            <input type="checkbox" value={"react"} onChange={handle} /> react


            <h2>Selected Skills:</h2>

            {skills.map((skill) => {
                return <p key={skill}>{skill}</p>;
            })}

        </div>
    )
}

export default Checkbox;
Enter fullscreen mode Exit fullscreen mode

Top comments (0)