Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React.js - how to set state on form submit?

Newbie React question - I've got myself thoroughly confused trying to follow the docs.

I want a simple text input that on button click, displays the input value below the form. Pretty simple, right?

This is my component so far:

export default class TextInput extends React.Component {
  constructor(props) {
    super(props);
    this.state = {value: ''};
    this.handleSubmit = this.handleSubmit.bind(this);
  }

  handleSubmit(event) {
    event.preventDefault();
    this.setState({ value: event.target.value });
  }

  render() {
    return (
      <div>
      <form onSubmit={this.handleSubmit}>
        <label>
          <input type="text"  value='' />
        </label>
        <input type="submit" value="Submit" />
      </form>
      <p>{ this.state.value }</p>
      </div>
    );
  }
}

However, it doesn't work at all - the form doesn't display anything when the user types.

What am I doing wrong?

like image 333
Richard Avatar asked Dec 24 '22 16:12

Richard


1 Answers

Changes:

1. You need to remove the value='' from input element otherwise it will not allow you to type any thing, you are not using any onChange function also.

Ways of using elements:

Controlled Component: Define a onChange function and value property and update that value inside that change function.

Uncontrolled Component: Don't define the value property, use ref to get the value of element.

2. Use ref with input element to get it's value in onSubmit function.

Check this:

class TextInput extends React.Component {
  constructor(props) {
    super(props);
    this.state = {value: ''};
    this.handleSubmit = this.handleSubmit.bind(this);
  }

  handleSubmit(event) {
    event.preventDefault();
    this.setState({ value: this.element.value });
  }

  render() {
    return (
      <div>
      <form onSubmit={this.handleSubmit}>
        <label>
          <input type="text" ref={el => this.element = el} />
        </label>
        <input type="submit" value="Submit" />
      </form>
      <p>{ this.state.value }</p>
      </div>
    );
  }
}

ReactDOM.render(<TextInput/>, document.getElementById('app'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

<div id='app'/>
like image 108
Mayank Shukla Avatar answered Dec 31 '22 02:12

Mayank Shukla