React - TextArea

About

HTML - Textarea in React

Type

Controlled Component

The react forms components textarea accept a value attribute that is used to implement a controlled component.

  • In HTML, a <textarea> element defines its text by its children.
  • In React, a <textarea> uses a value attribute instead. This way, a form using a <textarea> can be written very similarly to a React form that uses a single-line input. See React - Input Element

Example Controlled Component

Example of a form implemented as a controlled component written in a class syntax

class EssayForm extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      value: 'Please write an essay about your favorite DOM element.'
    };

    this.handleChange = this.handleChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
  }

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

  handleSubmit(event) {
    alert('An essay was submitted: ' + this.state.value);
    event.preventDefault();
  }

  render() {
    return (
      <form onSubmit={this.handleSubmit}>
        <label>
          Name:
          <textarea cols="50" rows="3" value={this.state.value} onChange={this.handleChange} />
        </label>
        <input type="submit" value="Submit" />
      </form>
    );
  }
}


ReactDOM.render(
  <EssayForm />,
  document.getElementById('root')
);
<div id="root"></div>

Powered by ComboStrap