1

Am trying to build form inputs in reactjs. the code below works for just one form inputs.

Now I want to add two more form inputs as per

Firstname <input type="text" id="fname" name="fname"><br>
Lastname <input type="text" id="lname" name="lname"><br>

below is the working code that I want to implement the two form inputs above. source

https://reactjs.org/docs/forms.html

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

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

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

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

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

2 Answers 2

1

The best way I've found to manage forms in React is to make sure each of your <input> tags has a name value. Then ensure that your component's state has fields for each input that matches the name exactly.

In your onChange handler, you can then say:

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

This will update the state with change to any of the inputs, and apply the change to that specific state value.

Then for handleSubmit, you send those values from state to where ever you need to process the form information.

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

Comments

0

try this one

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

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.