New on programming and trying to make a login form - javascript

I have some basic knowledge in programming and web-development.
I'm just trying something on Reactjs and already tried to read some documentation. I want to keep the code as simple as possible.
What I'm trying is just a validation if the text in the input field is "xyz" but somehow the validation is always wrong. Sometimes the if statement is true even with the wrong input.
What am I missing and how can I do it better?
import React from 'react';
class LoginForm extends React.Component {
constructor(props){
super(props);
this.state = {username:'' , password:''};
}
Submit = (event)=> {
event.preventDefault();
let user=this.state.username;
if(user == "xyz"){
alert("This works!");
} else{
alert("not working :/");}
}
render() {
return (
<form className="LoginForm" onSubmit={this.Submit}>
<p> Enter here</p>
<input type="text"/>
<input type="submit"/>
</form>
)
}}export default LoginForm

You currently are not capturing the onChange of the input. You must create an onChange event handler like so:
import React from "react";
class LoginForm extends React.Component {
constructor(props) {
super(props);
this.state = { username: "", password: "" };
}
formValidation = () => {
let errors = {};
if (!this.state.username) {
errors.username = "username must not be empty";
}
if (!this.state.password) {
errors.password = "password Must not be empty";
}
return errors;
};
handleInputChange = (field) => (e) =>
this.setState({ [field]: e.target.value });
Submit = (event) => {
event.preventDefault();
let errors = this.formValidation();
if (errors.username) {
alert(errors.username);
}
if (errors.password) {
alert(errors.password);
}
if (!errors.username && !errors.password) {
alert("success");
}
};
render() {
console.log(this.state.username);
return (
<form className="LoginForm" onSubmit={this.Submit}>
<p> Enter here</p>
<input
onChange={this.handleInputChange("username")}
value={this.state.username}
type="text"
placeholder="username"
/>
<input
onChange={this.handleInputChange("password")}
value={this.state.password}
type="text"
placeholder="password"
/>
<input type="submit" />
</form>
);
}
}
export default LoginForm;
I also created a formValidation function that returns an error object which to me is a bit cleaner.
Here is a code pen to see the code in action: https://codesandbox.io/s/determined-morning-rpzd2?file=/src/App.js
EDIT: I have updated the answer for a use case involving both inputs.

Related

React TypeError:Cannot read property 'text' of undefined

I am working on some project but I really stuck on this problem. Why I get this error like TypeError: Cannot read property 'text' of undefined, when my program update state onChange but when I clicked on submit button I get this mess, Please help me out.
my code snippet:
import React, { Component } from "react";
import { Form, Button, Input, Label } from "semantic-ui-react";
class FormField extends Component {
constructor() {
super();
this.state = {};
}
handleChange = event => {
this.setState({ [event.target.name]: event.target.value });
};
handleSubmit(event) {
event.preventDefault();
const { text } = this.state;
console.log(text);
}
textToCode() {}
render() {
return (
<Form onSubmit={this.handleSubmit}>
<Form.Field>
<Label>Enter Text</Label>
<Input
name="text"
value={this.state.text}
onChange={this.handleChange}
/>
</Form.Field>
<Form.Field>
<Button
type="submit"
>
Submit
</Button>
</Form.Field>
<Form.Field>
<input disabled />
</Form.Field>
</Form>
);
}
}
export default FormField;
handlesubmit isn't being passed properly to the event handler. You can write () => this.handlesubmit() in stead.

Perform HTML Input Validation on React Button Click

This is a simplified scenario.
I have a form with a required input field and a button. The button has an onClick React handler and is of type "button". I want the browser to check the HTML fields and do some initial validation (like it would do if no React were involved and the button were of type "submit"). I imagine I should do something in the handler function, but I am not sure what.
A few things I tried:
Changing the button to type "submit" does perform the check, but also calls the handler, which does not know whether the check succeeded or failed
Adding the handler on the form instead works, but makes the real example harder to maintain because I have a lot of buttons
Thank you
<div id="app"></div>
class MyClass extends React.PureComponent {
render() {
return (
<form action="#">
<input type="text" required/>
<button type="button" onClick={e => this.handle(e)}>Press</button>
</form>
)
}
handle(event) {
// What should I do here?
}
}
ReactDOM.render(<MyClass />, document.querySelector("#app"))
https://jsfiddle.net/89wr3ot4/
It looks like form has a checkValidity() and reportValidity() API. The answer then becomes
class MyClass extends React.PureComponent {
render() {
return (
<form action="#" ref={this.formRef}>
<input type="text" required/>
<button type="button" onClick={e => this.handle(e)}>Press</button>
</form>
)
}
handle(event) {
const form = this.formRef.current;
if (!form.checkValidity()) {
form.reportValidity()
return
}
// Everything else
}
}
ReactDOM.render(<MyClass />, document.querySelector("#app"))
You need to create state for input value
const [inputValue, setInputValue] = useState(''); //for functional component
const inputHandler = (event) => setInputValue(event.target.value);
then
<input type='text' value={inputValue} onChange={inputHandler} />
and check in your 'handler' function what you want.
handle(event) {
if (inputValue.length > 0) //do what you want...
}
Following is working example which is modified from above jsfiddle
class MyClass extends React.Component {
state = { value: '', message: ''}
render() {
return (
<form action="#">
<input type="text" required value={this.state.value} onChange={e => this.setState({value: e.target.value})} />
<button type="button" onClick={e => this.handle(e)}>Press</button>
<p> {this.state.message }</p>
</form>
)
}
handle(event) {
// What should I do here?
const { value } = this.state;
if (value === '') {
this.setState({message: 'Invalid!, Please enter valid input'})
} else {
this.setState({message: 'Yeah!, Got Valid input'})
}
}
}
ReactDOM.render(<MyClass />, document.querySelector("#app"))

How do I make the text from an input field appear on the screen after it is submitted?

I would like to take whatever is entered into the input field and have it display on the screen after the user clicks submit. I know this seems super basic, but I am new to React. Thanks ahead of time!
import React, { Component } from 'react';
class TextInput extends Component {
constructor(props){
super(props);
this.state = { info: "", showName: false };
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleChange(evt) {
evt.preventDefault();
this.setState({ info: evt.target.value })
}
handleSubmit(evt){
evt.preventDefault();
}
render() {
return (
<div>
<form onSubmit={this.handleSubmit}>
<input
type="text"
value={this.state.info}
onChange={this.handleChange}/>
<button>Submit</button>
</form>
//text from input appears here
</div>
);
}
}
export default TextInput;
If I understand correctly, you only want to display the text after the user clicks submit. In this case, you can use handleSubmit to set a special value in the state submittedInfo for example, and then display that value.
import React, { Component } from 'react';
class TextInput extends Component {
constructor(props){
super(props);
this.state = { info: "", submittedInfo: "", showName: false };
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleChange(evt) {
evt.preventDefault();
this.setState({ info: evt.target.value })
}
handleSubmit(evt){
evt.preventDefault();
this.setState({submittedInfo: this.state.info})
}
render() {
return (
<div>
<form onSubmit={this.handleSubmit}>
<input
type="text"
value={this.state.info}
onChange={this.handleChange}/>
<button>Submit</button>
</form>
//text from input appears here
<div>{this.state.submittedInfo}</div>
</div>
);
}
}
export default TextInput;
Another approach could be to store in the state a boolean isSubmitted, signifying whether or not the user has submitted the form, and then displaying this.state.info if isSubmitted is true
You already has state like,
this.state = { info: "", showName: false };
You can use showName state to show your text,
return (
<div>
<form onSubmit={this.handleSubmit}>
<input
type="text"
value={this.state.info}
onChange={this.handleChange}/>
<button>Submit</button>
</form>
//text from input appears here
{this.state.showName && <div>{this.state.info}</div>}
</div>
);
And your handleSubmit function should be,
handleSubmit(evt){
evt.preventDefault();
this.setState({showName:true})
}

Triggering form's submit event manually in React doesn't check required inputs

im trying to find a way to trigger the submit event manually, just like a button with type="submit" would.
I found a way to do that, from another post here, but unfortunately it doesn't check if the required inputs contain values and submits the form even when no text was typed into the input:
https://codesandbox.io/s/q92855nz3w
or
import React from "react";
import { render } from "react-dom";
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}>
<div onClick={this.handleSubmit}>SOME DIV</div>
<label>
Name:
<input
type="text"
value={this.state.value}
onChange={this.handleChange}
required
/>
</label>
<input type="submit" value="Submit" />
</form>
);
}
}
render(<NameForm />, document.getElementById("root"));
Thanks for any help in advance!
Found a solution to my question:
var form = document.getElementById("form");
form.reportValidity();

My inputs start with weird values

I've created very simple form for user to sign in. Here is my code:
import React,{ Component } from 'react';
class SignIn extends Component {
constructor(props) {
super(props);
this.state = {
login:"",
pass:""
}
}
signIn = (e) =>{
e.preventDefault();
alert("in")
}
handleChange = (propertyName) => (e) => {
const state = this.state;
const newState = {
...state,
[propertyName]: e.target.value
};
this.setState(newState);
}
render() {
return (
<div className="text-center">
<form onSubmit={this.signIn}>
<input type="text" id="login" onChange={this.handleChange('login')} value={this.state.login} placeholder="login"/>
<br />
<input type="password" id="pass" onChange={this.handleChange('pass')} value={this.state.pass} placeholder="pass"/>
<br />
<input type="submit" value="sign in" disabled={((this.state.login == "") && (this.state.pass == ""))
? true
: false}/>
</form>
</div>
);
}
}
export default SignIn;
For some reason every time I start my app these inputs already have some text inside. "login" always have "localhost" and "pass" contains some random numbers and letters. Can someone explain me where are these values comming from?
These fields are auto-populated by browser. See explanation here: https://developers.google.com/web/updates/2015/06/checkout-faster-with-autofill
Also you might be interested in this question of how people fighting with it :)
Chrome Browser Ignoring AutoComplete=Off

Categories

Resources