I have below code and i want to get the values entered in user name and password textbox and send them to node js service. But I dont know how to do that.
Things is that nothing is working. I can only render the page but functions are not working and not able to get the values as well from the textbox. I am very much new to react.
import { FormGroup} from "react-bootstrap";
import "./Login.css"
import "bootstrap/dist/css/bootstrap.min.css"
class LoginClassComponent extends React.Component {
constructor(props) {
super(props);
console.log(props);
this.state = {
username: '',
password: ''
}
this.handleTextChange = this.handleTextChange.bind(this);
this.handleValidation = this.handleValidation.bind(this);
}
handleTextChange = (event) => {
this.setState({ userName: event.target.value });
this.setState({ password: event.target.value });
}
handleValidation = (event) => {
console.log(this.props.userName);
if (!this.state.username) {
this.setState({ error: 'Please enter User Name' });
event.preventDefault();
}
else if (!this.state.password) {
this.setState({ error: 'Please enter Password' });
event.preventDefault();
}
else {
this.setState({ error: "" });
}
}
render() {
const {username, password} = this.props;
return (
<div className="Login">
<form >
<FormGroup controlId="email" bsSize="large">
<label htmlFor="exampleInputUserName"><b>User Name</b></label>
<input type="username" className="form-control" id="exampleInputUserName" value={this.props.userName} onChange={this.handleTextChange} placeholder="Enter User Name"></input>
<div><br></br></div>
</FormGroup>
<FormGroup controlId="password" bsSize="large">
<label htmlFor="exampleInputPassword"><b>Password</b></label>
<input type="password" className="form-control" id="exampleInputPassword" value={this.props.password} onChange={this.handleTextChange} placeholder="Enter Password"></input>
<div><br></br></div>
</FormGroup>
<button type="submit" onClick={this.handleValidation} className="btn btn-info">Login</button>
<button type="submit" className="btn btn-danger">Cancel</button>
<div><br></br></div>
<div id="errorDiv">
{(this.state.error !== '') ? <span style={{ color: "red" }}>{this.state.error}</span> : ''}
</div>
</form>
</div>
)
}
}
export default LoginClassComponent;
You can solve your problem 2 ways:
First, you can create 2 seperate onChange methods to update your username/password state
or, even better : add name tag to your form inputs:
name = userName
in your username input and
name = password
for password input.
Then make a method that triggers after onChange Event
function example(e){
this.setState({
[e.target.name] : [e.target.value]
})
}
Make sure that names of your username and password forms are the same as attributes in your state.
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