0

I have 3 inputs whose value I save and click on my btn, I would like to clear these inputs.......

my function that saves the value of one of my inputs:

onChangeIdentity = (event) => {
this.newPlayer = Object.assign({}, this.newPlayer, { strPlayer: 
event.target.value})
 }

my input:

<Input style={{width:'30%'}} onChange={ this.onChangeIdentity } 
 ref='myFormRef' value={ this.newPlayer.strPlayer } type='text' 
 placeholder='Nom & Prenom'/>

and the function that must clear my input:

addPlayer = () => {
  console.log('my new Player: ' , this.newPlayer);
  this.setState({
   teamPlayers: [...this.state.teamPlayers, this.newPlayer]
 })

this.refs.myFormRef.value = ""
 }

I tried several ways to declare my refs but nothing works..... any ideas?

2
  • When you say "clear my input," do you mean the UI surface in the browser, or do you mean something else? Commented Jan 20, 2019 at 17:35
  • @robert-harvey yes it's the ui surface Commented Jan 20, 2019 at 17:44

1 Answer 1

1

You input's values are driven by the state of the component value={this.newPlayer.strPlayer}. If you want to clear the input's value you need to clear the state which maps to it, for example:

this.setState({newPlayer: {strPlayer: ''}});

After setting the state, the component updates automatically and renders the input as empty.

Here is a full example component:

class MyComponent extends Component {
  state = {
    inputValue: ""
  };

  render() {
    return (
      <div>
        <input
          type="text"
          value={this.state.inputValue}
          onChange={event => this.setState({ inputValue: event.target.value })}
        />
        <button
          onClick={() => {
            /* submit this.state.inputValue */
            this.setState({ inputValue: "" }); // reset input value
          }}
        >
          submit
        </button>
      </div>
    );
  }
}
Sign up to request clarification or add additional context in comments.

1 Comment

great, that was it ;)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.