1

I'm working on a blog and on the top right corner I want the user to be able to set their own display name. I have it so there's an input in place so the user can set a display name and press enter. After the user puts in a name and hits enter I want that name to be set in stone. I have everything mostly working however I'm using e.target.value which updates constantly. So if the user was named Dagger it's setting the display name to D. I want it so the name is only updated after I press enter but I can't seem to figure it out. Please advice.

const [username, setUsername] = useState("");

{username ? (
  <span className="username">{username} ▼</span>
) : (
  <form>
    <label>
      <input type="text" onChange={(e) => setUsername(e.target.value)}></input>
    </label>
  </form>
)}
Mario Petrovic
  • 7,500
  • 14
  • 42
  • 62
Dagger
  • 291
  • 7

3 Answers3

2

Try this:

Get the value of input text when enter key pressed

Instead of using onChange, use the onkeydown and check which key was pressed.

2

Instead of onChange, use onKeyDown and when Enter is pressed, set the username.

  const [username, setUsername] = useState("");
  const onKeyDown = ({key, target}) => {

    if (key == "Enter") {
      setUsername(target.value)
    }
  }
  <input type="text" onKeyDown={onKeyDown} />

Try this

const Username = () => {
  const [username, setUsername] = useState("");
  
  const onKeyDown = ({key, target}) => {
   
    if (key == "Enter") {
      setUsername(target.value)
    }
  }

  if (username !== "") {
    return <span className="username">{username} ▼</span>
  }

  return (
    <form>
      <label>
        <input type="text" onKeyDown={onKeyDown} />
      </label>
    </form>
  )
}

mahan
  • 12,366
  • 5
  • 48
  • 83
1

a messy solution would be to add another state inside the "span" tag and your code would be something like this

const [username, setUsername] = useState("");
const [username2,setUsername2]= useState("")

{username2 ? (
  <span className="username">{username2} ▼</span>
) : (
  <form onSubmit={(e)=> {
e.preventDefautlt();
setUsername2(username);

}>
    <label>
      <input type="text" onChange={(e) => setUsername(e.target.value)} value={username}></input>
    </label>
  </form>
)}

with this code whenever you press enter the username2 will be set with the input value and hence it appears