0

I am new to react js.

I have several inputs in my form and considering controllable input approach in React , I am trying to do the job with one event handler to every other inputs. I took some references in stack overflow and come to this. Still not able to figure it out why I am unable to write inside my input box.

Here is my code.

import React, {Component} from 'react';
import { Grid, Row, Col , Button } from 'react-bootstrap';

class ContactForm extends Component {
  constructor(props) {
    super(props);

    this.state = {
      name: '' ,
      email: ''
    };
    this.handleChange = this.handleChange.bind(this);
  }

  handleChange(e) {
      this.setState({[e.target.name]: e.target.value})
  }

  render() {
    return (
      <form>
          <input name="input1"  value={this.state.name}  onChange={this.handleChange}/>
          <input name="input2" value={this.state.email} onChange={this.handleChange} />
          <p>{this.state.name}, {this.state.email}</p>
      </form>
    );
  }
}


export default ContactForm;

2 Answers 2

1

You're using the name attribute to identify the input, but you're reading the wrong values in the render function, "name" and "email" instead of "input1" and "input2"

You can do this instead:

<input name="input1"  value={this.state.input1}  onChange={this.handleChange}/>
<input name="input2" value={this.state.input2} onChange={this.handleChange} />

or

<input name="name"  value={this.state.name}  onChange={this.handleChange}/>
<input name="email" value={this.state.email} onChange={this.handleChange} />

You'd also have to change this :

this.state = {
  name: '' ,
  email: ''
};

in the constructor if you're using the first option.

Sign up to request clarification or add additional context in comments.

Comments

0

I would use ref to achieve this:

handleChange(e) {
      const {input1, input2} = this.refs;
      //do what ever you want with the values

  }

  render() {
    return (
      <form>
          <input name="input1"  value={this.state.name} ref="input1" />
          <input name="input2" value={this.state.email} ref="input2" onChange={this.handleChange} />
          <p>{this.state.name}, {this.state.email}</p>
      </form>
    );
  }
}

Also, I would use a submit button, or something like that, instead of an event listener on one or two of the inputs

Comments

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.