Search code examples
reactjsreact-hooksantd

antd <Input> value is not reset after creating a new one


I have given a list on teams I want to display using antd Input fields. An additional Input-field is created to be able to add a new team. When I press 'enter' a given team should be updated or a new team should be added and a new, empty Input field should be created. My code looks like the following

`import { useState } from 'react'

import { Input } from 'antd'

const TeamListCreator = () => {
  const [teamslist, setTeamslist] = useState(['Team1'])
  const [newTeam, setNewTeam] = useState('')

  const teamChange = (index) => {
    const updatedTeams = [...teamslist]
    updatedTeams[index] = newTeam
    setTeamslist(updatedTeams)
  }

  return (
    <div>
      <h2>Teams hinzufügen</h2>
      <p>Aktuell vohanden Teams: {teamslist.length}</p>
      {teamslist.map((team, index) => (
        <Input
          key={index}
          defaultValue={team}
          onChange={(e) => setNewTeam(e.target.value)}
          onPressEnter={(index) => teamChange(index)}
        />
      ))}
      <Input
        key={() => 'newTeam' + teamslist.length}
        placeholder="Neues Team"
        onChange={(e) => setNewTeam(e.target.value)}
        onPressEnter={() => {
          if (newTeam.trim() !== '') {
            setTeamslist([...teamslist, newTeam])
            setNewTeam('')
          }
        }}
      />
    </div>
  )
}

export default TeamListCreator`

It seems to work fine. But when I create a new team pressing 'enter' in the newTeam-Input field, the newly created (empty) Input field contains the value of the former "newTeam" Input field.

My expectation was, that the value is empty and the placeholder is used.

For me it also seems to be a rendering issue, as the value of field is empty.

Has anyone an idea, how to fix this?

My expectation was, that the value is empty and the placeholder is used.

For me it also seems to be a rendering issue, as the value of field is empty.


Solution

  • you have to use: value={newTeam}

    for second input