reactjs

Interview Question 1

/* Can you explain the differences between Component 1 and Component 2
 * Can you explain the differences between Component 2 and Component 3
 */

//Component 1
class Component1 extends React.Component {
  constructor(props) {
    super(props);
    this.handleSubmit = this.handleSubmit.bind(this);
    this.input = React.createRef();
  }

  handleSubmit(event) {
    alert("A name was submitted: " + this.input.current.value);
    event.preventDefault();
  }

  render() {
    return (
      <form onSubmit={this.handleSubmit}>
        <label>
          Name:
          <input type="text" ref={this.input} defaultValue={"Bob"} />
        </label>
        <input type="submit" value="Submit" />
      </form>
    );
  }
}

//Component 2
//Here I am maintaining value in the state
class Component2 extends React.Component {
  constructor(props) {
    super(props);
    this.handleSubmit = this.handleSubmit.bind(this);
    this.updateValue = this.updateValue(this);
    this.state = { value: "Bob" }; //Different from Componenet1
    this.input = React.createRef();
  }

  handleSubmit(event) {
    alert("A name was submitted: " + this.state.value);
    event.preventDefault();
  }

  //Different from Componenet1
  updateValue(e) {
    const value = e.target.value;
    this.setState({ value }); //Change value in state
  }

  render() {
    return (
      <form onSubmit={this.handleSubmit}>
        <label>
          Name:
          <input
            type="text"
            ref={this.input}
            value={this.state.value} //Different from Componenet1
            onChange={this.updateValue} //Different from Componenet1
          />
        </label>
        <input type="submit" value="Submit" />
      </form>
    );
  }
}

//Component 3
class Component3 extends React.Component {
  constructor(props) {
    super(props);
    this.handleSubmit = this.handleSubmit.bind(this);
    this.updateValue = this.updateValue(this);
    this.state = { value: "Bob" };
    this.input = React.createRef();
  }

  handleSubmit(event) {
    alert("A name was submitted: " + this.state.value);
    event.preventDefault();
  }

  //Different from above component
  updateValue(e) {
    const value = e.target.value;
    this.state.value = value; //Change value in the state
  }

  render() {
    return (
      <form onSubmit={this.handleSubmit}>
        <label>
          Name:
          <input
            type="text"
            ref={this.input}
            value={this.state.value}
            onChange={this.updateValue}
          />
        </label>
        <input type="submit" value="Submit" />
      </form>
    );
  }
}
Was this helpful?