I would like to know whether this is good practice or whether I should rather design this app differently. I am particulary concerned with the two 'handleChange' functions, and am wondering whether this could be simplified somehow. Other advice is also welcome, of course.
user-add.js:
import React, {Component} from 'react';
import {bindActionCreators} from 'redux';
import {connect} from 'react-redux';
import {createUser} from '../actions/index'
class UserCreate extends Component {
constructor(props, context) {
super(props, context);
this.state = {
inputText: 'Helluuuu'
}
}
handleChangeFirstName(event) {
console.log(event.target.value);
this.setState({
inputTextFirstName: event.target.value
})
}
handleChangeLastName(event) {
console.log(event.target.value);
this.setState({
inputTextLastName: event.target.value
})
}
render() {
return (
<div>
<h2> Add User </h2>
<table className="userTable">
<tbody>
<tr>
<td>First Name:</td>
<td>Last Name:</td>
</tr>
<tr>
<td>
<input type="text"
placeholder="Hello!"
value={this.state.inputTextFirstName}
onChange={this.handleChangeFirstName.bind(this)}/>
</td>
<td>
<input type="text"
placeholder="Hello!"
value={this.state.inputTextLastName}
onChange={this.handleChangeLastName.bind(this)} />
</td>
</tr>
</tbody>
</table>
<button onClick={() =>this.props.createUser()}>Submit</button>
</div>
);
}
}
function mapStateToProps(state) {
return {
user: state.activeUser
};
}
function matchDispatchToProps(dispatch){
return bindActionCreators({createUser: createUser}, dispatch);
}
export default connect(mapStateToProps, matchDispatchToProps)(UserCreate);
Of course you can reduce this to only one handleChange
method and can consume as many input fields you want with that single method.
Also, I don't think you need any third party package for this.
In your render method:
<input
type="text"
name="firstName"
placeholder="First Name!"
value={this.state.firstName}
onChange={this.handleChange.bind(this)}
/>
<input
type="text"
name="lastName"
placeholder="Last Name!"
value={this.state.lastName}
onChange={this.handleChange.bind(this)}
/>
Handle Change Method
handleChange(e) {
this.setState({ [e.target.name] : e.target.value });
}
Much cleaner.
Beware that checkboxes work differently!
From the React docs:
handleInputChange(event) {
const target = event.target;
const value = target.type === 'checkbox' ? target.checked : target.value;
const name = target.name;
this.setState({
[name]: value
});
}
More concise:
handleInputChange({ target }) {
const value = target.type === 'checkbox' ? target.checked : target.value;
this.setState({ [target.name]: value });
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With