Prevent an empty submission in React - reactjs

How would I go about preventing someone from adding nothing my to do list?
AppTodo.JS
import React, { Component } from "react";
import PropTypes from "prop-types";
export class AddTodo extends Component {
state = {
title: ""
};
onSubmit = e => {
e.preventDefault();
if (this.state.addTodo === "") {
alert("??");
} else {
this.props.addTodo(this.state.title);
this.setState({ title: "" });
}
};
onChange = e => this.setState({ title: e.target.value });
render() {
return (
<form onSubmit={this.onSubmit} stlye={{ display: "flex" }}>
<input
type="text"
name="title"
style={{ flex: "10", padding: "5px" }}
placeholder="Add Things Todo..."
value={this.state.title}
onChange={this.onChange}
/>
<input
type="submit"
value="Submit"
className="btn"
style={{ flex: "1" }}
/>
</form>
);
}
}
// Prop Types
AddTodo.propTypes = {
addTodo: PropTypes.func.isRequired
};
export default AddTodo;
I am new to React, just doing it for fun and spent a few hours trying to make conditionals work within the onSumbit method and even in the render() method, but can't seem to make anything work.
Thanks ahead of time.

You do not have an addTodo variable in your state, but you do have a title variable.
Change this.state.addTodo === "" to this.state.title === "" and it will work as expected.
class AddTodo extends React.Component {
state = {
title: ""
};
onSubmit = e => {
e.preventDefault();
if (this.state.title === "") {
alert("??");
} else {
this.props.addTodo(this.state.title);
this.setState({ title: "" });
}
};
onChange = e => this.setState({ title: e.target.value });
render() {
return (
<form onSubmit={this.onSubmit} stlye={{ display: "flex" }}>
<input
type="text"
name="title"
style={{ flex: "10", padding: "5px" }}
placeholder="Add Things Todo..."
value={this.state.title}
onChange={this.onChange}
/>
<input
type="submit"
value="Submit"
className="btn"
style={{ flex: "1" }}
/>
</form>
);
}
}
ReactDOM.render(
<AddTodo addTodo={todo => console.log(`Added todo: ${todo}`)} />,
document.getElementById("root")
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"></div>

Related

multiinput from submission in react js

I am trying to submit a form in react js I have multiple files
this.state = {
allValues: [],
};
changeHandler = (e) => {
this.setState({ ...this.allValues, [e.target.name]: e.target.value });
};
onsubmbit = (e) => {
e.preventDefault();
console.log(this.state.allValues);
};
<form onSubmit={this.onsubmbit}>
<input type='text' name='bloodsugar' onChange={this.changeHandler} value='' />
<input
type='text'
name='bloodpressure'
onChange={this.changeHandler}
value=''
/>
<button type='submit' style={styles.subbtn}>
Submit
</button>
</form>;
I am trying to submit a form in react js I have multiple files
I am trying to submit this form
console.log(this.state.allValues); when i console log it in submit function i want data as
{
bloodsugar:data of bloodsugar,
bloodpressure:data of bloodsugar,
}
when I console log it in submit function I want data like this
You have to set the value of each input field from the state that you set with changeHandler method. Additionally, you need to update the changeHandler method to update the state.allValues as follows.
(Following is the example code I used to test locally. Do the necessary modifications to fit it to your implementation)
import React, { Component } from "react";
export default class App extends Component {
constructor(props) {
super(props);
this.state = {
allValues: {
bloodsugar: "",
bloodpressure: "",
},
};
}
changeHandler = (e) => {
this.setState({
allValues: { ...this.state.allValues, [e.target.name]: e.target.value },
});
};
onsubmbit = (e) => {
e.preventDefault();
console.log(this.state.allValues);
};
render() {
return (
<form onSubmit={this.onsubmbit}>
<div>
<div style={{ fontSize: "4rem", padding: "15px" }}>
<i className="fa fa-level-up"></i>
</div>
<div style={{ padding: "10px" }}>
<strong>Enter your blood sugar level</strong>
<br />
<input
type="text"
name="bloodsugar"
onChange={this.changeHandler}
value={this.state.allValues.bloodsugar}
/>
</div>
</div>
<div>
<div style={{ fontSize: "4rem", padding: "15px" }}>
<i className="fa fa-area-chart"></i>
</div>
<div style={{ padding: "10px" }}>
<strong>Enter your blood pressure level</strong>
<br />
<input
type="text"
name="bloodpressure"
onChange={this.changeHandler}
value={this.state.allValues.bloodpressure}
/>
</div>
</div>
<button type="submit">Submit</button>
</form>
);
}
}

how do I hide/display the submit button in React JS

I am completely new to React JS, I have no Idea how to do in ReactJS.
I have to hide the Submit button initially, when keyin to dates fields then Submit button should be display.
class MyForm extends React.Component {
constructor(props) {
super(props);
this.state = { startdate: '', enddate: '' };
}
mySubmitHandler = (event) => {
event.preventDefault();
alert("You are submitting " + this.state.startdate +"and"+ this.state.enddate);
}
myChangeHandler = (event) => {
this.setState({startdate: event.target.value});
}
myEndDate = (event) => {
this.setState({enddate: event.target.value});
}
render() {
return (
<form onSubmit={this.mySubmitHandler}>
<img src="C:\\Users\\A9002255\\Desktop\is.jpg"></img>
<h2>Please select the Date range of .CSV </h2>
<input
type='date'
onChange={this.myChangeHandler}
/>
<span> </span>
<input
type="date"
onChange={this.myEndDate}
/>
<div>
<input
type='submit' value="Download" class="bi bi-cloud-arrow-down" style={{ width: '10%', height: 30}}
/>
</div>
</form>
);
}
}
ReactDOM.render(<MyForm />, document.getElementById('root'));
export default MyForm;
You can add check on base of start and end dates of your state.
Try following code
class MyForm extends React.Component {
constructor(props) {
super(props);
this.state = { startdate: '', enddate: '' };
}
mySubmitHandler = (event) => {
event.preventDefault();
alert("You are submitting " + this.state.startdate +"and"+ this.state.enddate);
}
myChangeHandler = (event) => {
this.setState({startdate: event.target.value});
}
myEndDate = (event) => {
this.setState({enddate: event.target.value});
}
render() {
return (
<form onSubmit={this.mySubmitHandler}>
<img src="C:\\Users\\A9002255\\Desktop\is.jpg"></img>
<h2>Please select the Date range of .CSV </h2>
<input
type='date'
onChange={this.myChangeHandler}
/>
<span> </span>
<input
type="date"
onChange={this.myEndDate}
/>
<div>
{this.state.startdate && this.state.enddate && <input
type='submit' value="Download" class="bi bi-cloud-arrow-down" style={{ width: '10%', height: 30}}
/>}
</div>
</form>
);
}
}
ReactDOM.render(<MyForm />, document.getElementById('root'));
export default MyForm;

Basic posting of data from frontend to backend

I'm making my first steps with React and got stuck on POST-ing data from a simple user registration form to the backend API. For some reason, when I press the "Register" button in the form and want to call handleSubmit, it doesn't get called and instead throws some error.
import React, { Component } from 'react';
import axios from 'axios';
import { Container, Row, Col } from 'reactstrap';
import NavBar from '../NavBar';
class RegistrationForm extends Component {
constructor(props)
{
super(props)
this.state = {
name: '',
display: '',
email: '',
pswd: ''
}
console.log("RegistrationForm constructor");
};
changeNameValue = (e) => { this.setState({ name: e }) }
changeDisplayValue = (e) => { this.setState({ display: e }) }
changeEmailValue = (e) => { this.setState({ email: e }) }
changePswdValue = (e) => { this.setState({ pswd: e }) }
handleSubmit = () => {
console.log("handleSubmit()");
const data = {
username: this.state.name,
displayname: this.state.display,
email: this.state.email,
password: this.state.pswd
}
axios.post(
'http://localhost:9000/api/registeruser',
{ body: JSON.stringify(data) }
).then(res => console.log("Posted"));
}
render() {
var logoImage = require('../../images/logo_v3_150.png');
return (
<div style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', height: '100vh' }}>
<Container>
<Row>
<img src={logoImage} width='150' height='184' /><br />
</Row>
<Row>
<form>
<input value={this.state.name} onChange={(e) => this.changeNameValue(e.target.value)} placeholder='Username' /><br />
<input value={this.state.display} onChange={(e) => this.changeDisplayValue(e.target.value)} placeholder='Display Name' /><br />
<input value={this.state.email} onChange={(e) => this.changeEmailValue(e.target.value)} placeholder='Email' /><br />
<input value={this.state.pswd} onChange={(e) => this.changePswdValue(e.target.value)} placeholder='Password' /><br />
<button onClick={this.handleSubmit}>Register</button>
</form>
</Row>
<Row>
<NavBar />
</Row>
</Container>
</div>
);
}
}
export default RegistrationForm;
The error (only this message in the Firefox's Dev Tools):
This is probably something silly that I missed but I can't figure it out by myself.

How to show/hide div in React?

I want to show <div nameClass="showName"> when button is clicked and this.state.name's value is not null.
The showResult state check name's value is null or not, but this isn't work I guess.
I don't know how to fix it.
import React, { Component } from 'react';
class PhoneForm extends Component{
state = {
name : '',
showResults : false
}
handleChange = (e) => {
this.setState({
name: e.target.value
})
}
onClick=(e)=>{
this.setState({
showResults: this.state.name===null ? false : true
})
}
render(){
return (
<form>
<input
placeholder="name"
value={this.state.name}
onChange={this.handleChange}/>
<button onClick={this.onCkick}>클릭!</button>
<div nameClass="showName" style={{display:(this.state.showResults? 'block':'none')}}>{this.state.name}</div>
</form>
);
}}
export default PhoneForm;
You have a small typo in your render method. Your change event handler is called onClick, not onCkick.
You must also make sure to use preventDefault on the event when the form is submitted, or the browser will reload.
class PhoneForm extends React.Component {
state = {
name: "",
showResults: false
};
handleChange = e => {
this.setState({
name: e.target.value
});
};
onClick = e => {
e.preventDefault();
this.setState({
showResults: this.state.name === null ? false : true
});
};
render() {
return (
<form>
<input
placeholder="name"
value={this.state.name}
onChange={this.handleChange}
/>
<button onClick={this.onClick}>클릭!</button>
<div
nameClass="showName"
style={{ display: this.state.showResults ? "block" : "none" }}
>
{this.state.name}
</div>
</form>
);
}
}
ReactDOM.render(<PhoneForm />, 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>
When the input is empty it will show nothing hence we don't need to check whether the input has a value or not.
What is needed to to toggle the visibility for on the onClick function.
Set the <button/> type attribute to 'button' if you dont want to refresh the page all the time.
like: <button type="button" onClick={this.onClick}>클릭!</button>
Or trigger the preventDefault() on the event.
class PhoneForm extends React.Component {
state = {
name: "",
showResults: true
};
handleChange = e => {
this.setState({
name: e.target.value,
showResults: true
});
};
onClick = e => {
this.setState({
showResults: !this.state.showResults
});
};
render() {
return (
<form>
<input
placeholder="name"
value={this.state.name}
onChange={this.handleChange}
/>
<button type="button" onClick={this.onClick}>클릭!</button>
<div
nameClass="showName"
style={{ display: this.state.showResults ? "block" : "none" }}
>
{this.state.name}
</div>
</form>
);
}
}
ReactDOM.render(<PhoneForm />, 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>

Value property on input field changes after a second user interaction - React

I have a form with two input elements - one for name (type="text") and one for age (type="number"). I manage the form state in the parent component. I have my handler methods and everything set up. The form state changes when user types. Also the input value property on the name field receives its value based on the current state, but the number field does not receive it while user types but on a second interaction with the page (a click somewhere else let's say)
Here is my Form component:
const Form = (props) => {
return (
<div className="col-md-4 form">
<form id="myForm">
<div className="form-group">
<label>Please, enter your name</label>
<input onChange={props.inputChanged} id="name" type="text" className="form-control" name="name"
placeholder="Name" value={props.data.name}/>
</div>
<div className="form-group">
<label>How old are you?</label>
<input onChange={props.inputChanged} id="age" type="number" className="form-control" name="age"
placeholder="Age" value={props.data.age}/>
</div>
</div>
And the parent class based component which owns the state:
class DbControls extends Component {
//INITIAL STATE
state = {
name: '',
age: '',
greeting: 'hello',
role: 'admin'
}
//HANDLE USER INPUT FOR NAME AND AGE
inputHandler = (e) => {
if (e.target.id === 'name') {
this.setState({name: e.target.value})
} else if (e.target.id === 'age') {
this.setState({age: e.target.value})
}
}
//HANDE USER PREFERENCES FOR GREETING AND ROLE
selectHandler = (e) => {
if (e.target.id === 'greet') {
this.setState({greeting: e.target.value})
} else if (e.target.id === 'role') {
this.setState({role: e.target.value})
}
}
render() {
return (
<div className="container-fluid">
<div className="row">
<Form data={this.state} inputChanged={this.inputHandler} selectChanged={this.selectHandler}/>
<div className="col-md-6 table">
<Table tableFor="Admins table"/>
<Table tableFor="Moderators table"/>
</div>
</div>
</div>
);
}
}
I am not sure if this is an actual problem but I was just curious what might be the reason for that behavior?
As per some of your comments i understand that the real issue you are facing is the the DOM value attribute is not in sync with the value property.
This is by design, there is a lot of talk about this issue and it mostly related to the confusion people do with:
jsx value attribute / property
DOM (devtools html) value attribute
These are not the same thing.
There is another thing to consider, related to passwords exploit.
You can read this issue for better understanding and more details.
Simplify how the inputs are setting state based upon the input's e.target.name and e.target.value. By design, the DOM number input value will only update when unfocused, but state is always up-to-date.
Here's a working example: https://codesandbox.io/s/qzl5knl4kj
formInputs.js
import React, { Fragment } from "react";
export default ({ age, handleChange, name }) => (
<Fragment>
<label>Please, enter your name: </label>
<br />
<input
onChange={handleChange}
type="text"
className="uk-input"
name="name"
placeholder="Name"
value={name}
style={{ width: 300, marginBottom: 10 }}
/>
<br />
<label>How old are you?</label>
<br />
<input
onChange={handleChange}
type="number"
className="uk-input"
name="age"
placeholder="Age"
value={age}
style={{ width: 300, marginBottom: 10 }}
/>
<br />
</Fragment>
);
index.js
import React, { Component } from "react";
import { render } from "react-dom";
import FormInputs from "./formInputs";
import "uikit/dist/css/uikit.min.css";
import "./styles.css";
class App extends Component {
state = {
name: "",
age: "",
greeting: "hello",
role: "admin"
};
handleChange = ({ target: { name, value } }) => this.setState({ [name]: value });
handleFormClear = () => this.setState({ age: "", name: "" });
handleSubmit = e => {
e.preventDefault();
const { age, name } = this.state;
if (!age || !name) return;
alert(`Name: ${name}, Age: ${age}`);
};
render = () => (
<form onSubmit={this.handleSubmit} style={{ textAlign: "center" }}>
<h1>Mixed Input Fields</h1>
<FormInputs {...this.state} handleChange={this.handleChange} />
<button
style={{ marginBottom: 20, marginRight: 10 }}
type="submit"
className="uk-button uk-button-primary"
>
Submit
</button>
<button
style={{ marginBottom: 20 }}
type="button"
className="uk-button uk-button-danger"
onClick={this.handleFormClear}
disabled={!this.state.name && !this.state.age}
>
Clear
</button>
<div>
<pre style={{ margin: "auto", width: 300 }}>
<code>
Name: {this.state.name}
<br />
Age: {this.state.age}
</code>
</pre>
</div>
</form>
);
}
render(<App />, document.getElementById("root"));

Resources