2

How do align with DRY coding when handling onChange for an simple contact form in React application?

I would like to pass an param with the state that should be updated

For example, simply having 4 inputs [name, phone, email, text] require 4 different eventhandlers updating different states of component, which is not great.

 constructor(props) { super(props); this.state = { type: '', message: '', name: '', email: '', phone: '', content: '' }; } handleChange(e, state) { this.setState({state: e.target.value}); alert(state + " with val " + e.target.value) } 

This doesn't work and throwing an Cannot read property 'value' of undefined error

<input value={this.state.name} onChange={this.handleChange(name).bind(this)} id="firstName" name="firstName" autocomplete="off" type="text" required /> 

1 Answer 1

5

You need pass argument to handleChange like this

onChange={ this.handleChange.bind(this, name) } 

and signature for handleChange will be handleChange(state, e) {}


or you can use arrow function

onChange={ (e) => this.handleChange(e, name) } 

Update

Based on your problem description, I suppose you don't need pass additional argument, you can take input name(in this case I think input name and state name can be the same), and can do like so

class Form extends React.Component { constructor(props) { super(props); this.state = { // type: '', // message: '', name: '', email: '', // phone: '', // content: '' }; this.handleChange = this.handleChange.bind(this); } handleChange(e) { this.setState({ [e.target.name]: e.target.value }) } render() { return <div> <input value={this.state.name} onChange={ this.handleChange } name="name" autocomplete="off" type="text" required /> <input value={this.state.email} onChange={ this.handleChange } name="email" autocomplete="off" type="text" required /> <p>{this.state.name},{this.state.email}</p> </div> } }; ReactDOM.render(<Form />, document.getElementById('root'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script> <div id="root"></div>

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

1 Comment

@AlexanderT. the update looks like a best and simplest solution. Thank you for help and variety of options !

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.