Home > OS >  Understanding the useState and input logic
Understanding the useState and input logic

Time:05-31

im having trouble to get my UseState to show itself once i click a button, currently i have a function, that that use usestate and show my value on the screen, for example, when i write "miki" in the input box, it will show "miki" on the screen, however, it happens when i click the input box, and i want it to happen when im pressing the button, this is my code untill now:

import react, { useState } from "react";

export const ShoppingListPageContainer = () => {
    const [name, setName] = useState(``)
    const nameChange = (event) => {
        setName(event.target.value)
    }

    return <div>
        <input label="name: " id="name" onClick={nameChange} />
        <input type="number" name="quantity" />
        <button> Add </button>
        <p> {name} </p>
    </div>
}   

as u can see, the onClick is on the input and thats why it works when pressing the inputbox, but, when i switch the onClick location to the button, it shows nothing, because there arent any value inserted to the button, obviously, any help?

CodePudding user response:

You are using the onClick property (in onClick={nameChange}). This means your nameChange function gets called every time a user clicks into the input box.

You should change this to onChange={nameChange} and add the value={name} to the input:

<input label="name: " id="name" onChange={nameChange} value={name} />

This means that the nameChange function gets called every time the input changes. The value will also be set to name, so if anything else calls nameChange, it will be reflected in the input box.

CodePudding user response:

Use the onChange event in the input field. And use the useEffect hook and its dependency to get the current data

useEffect(() => {
  console.log('name', name);
}, [name])
<input type="string" onChanhe={(e:any) => nameChange(e.target.value)} />
<p>{name}</p>

  • Related