Walter Carrera
Walter Carrera

Reputation: 35

How do I get onChange to work with several form fields in Reactjs?

I'm trying to get this form to work, but when I try to type into the form fields, nothing happens.

At first, the text that I would input would appear on the fields simultaneously, and then I changed a couple things.

Now it does not work at all...

I'm thinking that it is an issue with onChange, but I'm not sure.

Here is the code:

handleChange = (event) => {
  let newState = {};

  newState[event.target.name] = event.target.value;

  this.setState(newState);
}

handleSubmit = (event) => {
  event.preventDefault();
  this.setState({
      title: '',
      description: '',
      dueDate: '',
      assignee: '',
      items: [...this.state.items, this.state.title, this.state.description, 
this.state.dueDate, this.state.assignee]
  });
}

render() {
  return (
    <div>
    <button onClick={this.openModal}>Add a Task</button>

    <ReactModal
        isOpen={this.state.modalIsOpen}
        onRequestClose={this.closeModal}
    >

        <div className='modalDialog'>
            <form className="App" onSubmit={this.handleSubmit}>
                Title: <input value={this.state.title} onChange={this.handleChange} />
                Description: <input value={this.state.description} onChange={this.handleChange} />
                Due Date: <input value={this.state.dueDate} onChange={this.handleChange} />
                Assignee: <input value={this.state.assignee} onChange={this.handleChange} />
                <button>Submit</button>
            </form>
            <button onClick={this.closeModal}>X</button>
        </div>
    </ReactModal>

    <List items={this.state.items} />
    </div>
);
}
}

const List = props => (
<ul>
    {props.items.map((item,index) => <li key={index}>{item}</li>)}
</ul>
);

export default App;

Thanks for the help!

Upvotes: 2

Views: 96

Answers (2)

Sagiv b.g
Sagiv b.g

Reputation: 31014

Your code should work well beside one little thing that is missing.
In your change handler your using event.target.name but you are missing the name attribute on those <input /> elements.
For example:

Title: <input name="title" value={this.state.title} onChange={this.handleChange} />

title attribute should be corresponding to the property on the state of course.

Upvotes: 1

Duncan Thacker
Duncan Thacker

Reputation: 5188

I suspect the problem is that your element does not have type="submit", so the form never submits. The onChange events are probably firing correctly (although as bennygenel points out, the input fields should have a "name" attribute to make your state changes work!)

Upvotes: 0

Related Questions