01. März 2022

Basic react component

Einfache React-Komponente, mit der eingegebene Texte als Liste ausgegeben werden.
class DisplayMessages extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      input: "",
      messages: [],
      error: "",
    };
  }

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

  submitMessage() {
    let newState;
    !this.state.input
      ? (newState = {
          error: "Please type in a message",
        })
      : (newState = {
          messages: [...this.state.messages, this.state.input],
          input: "",
          error: "",
        });
    this.setState(newState);
  }

  render() {
    const listItems = this.state.messages.map((msg, index) => {
      return <li key={index}>{msg}</li>;
    });
    return (
      <div>
        <h2>Type in a new Message:</h2>
        <input
          onChange={this.handleChange.bind(this)}
          value={this.state.input}
        />
        <button onClick={this.submitMessage.bind(this)}>Submit</button>
        <p>{this.state.error}</p>
        <ul>{listItems}</ul>
      </div>
    );
  }
}
freeCodeCamp