0
votes

currently trying to use setState to clear a controlled input,

adding a value to the input field and using setState to clear it

The function that clears the state

createNewBoard = (e) => {
  e.preventDefault();
  const newItem = { boardname: this.state.currentValue, todo: []};
  const updatedList = [...this.state.boards, newItem]
  this.setState({ 
    boards: updatedList, 
    currentValue: '' 
 });
}

passing down the props to the component

render() {
    return(
      <>
        { this.state.isBoardOpen ? 
        <ActiveCreateBoard 
          toggleCreateBoard={this.toggleCreateBoard} 
          onChange={this.onChange} 
          currentValue={this.currentValue}
          createNewBoard={this.createNewBoard} 
        /> : <CreateBoard toggleCreateBoard={this.toggleCreateBoard}/> }

        <ShowAllBoards boards={this.state.boards}/>
      </>
    )
  }

the component itself which is not updating the input field

const ActiveCreateBoard = ({ toggleCreateBoard, onChange, currentValue, createNewBoard }) => {
    return(
        <div className="card">
            <div className="card-body">
                <form onSubmit={createNewBoard}>  
                    <h4>Pick a board name</h4>
                    <input 
                    type="text" 
                    onChange={onChange} 
                    value={currentValue}/>
                </form>
            </div>
            <button onClick={toggleCreateBoard}>close</button>
        </div>
    )
}

this.setState is clearing the currentValue in state, but the value of the input field is not reflecting the update in state

1
Please add the line from render() that sets currentValue. - Chris G
Your code should work as it is if you are successfully destructring createNewBoard and onChange from this and currentValue from this.state. If possible, please share your whole component here (as a working copy). - devserkan
updated with some more information, thanks! - niinja no

1 Answers

0
votes

Your input field is not updating because you are passing down this.currentValue, which will be undefined:

<ActiveCreateBoard 
  toggleCreateBoard={this.toggleCreateBoard} 
  onChange={this.onChange} 
  currentValue={this.currentValue}
  createNewBoard={this.createNewBoard} 
/>

Instead, you need to pass down the value from state.

Change to use this.state.currentValue:

<ActiveCreateBoard 
  toggleCreateBoard={this.toggleCreateBoard} 
  onChange={this.onChange} 
  currentValue={this.state.currentValue} // <---
  createNewBoard={this.createNewBoard} 
/>