How to prevent adding empty task in react code? - javascript

I would like to prevent my application to prevent adding empty task. Following the code which adds new task in an array. May I ask please how to put condition to prevent adding empty task?
The application is built on Mozilla's guideline for the react app.
import React, {useState} from 'react';
function Form(props){
const [name, setName ] = useState('');
const [important, setImportant] = useState(false);
function handleChangeImportant(e){
console.log(e);
e.preventDefault();
setImportant(e.target.checked);
};
function handleChange(e) {
setName(e.target.value);
}
function handleSubmit(e){
e.preventDefault();
//alert('Moin');
props.addTask(name);
setName("");
}
return(
<form onSubmit={handleSubmit}>
<h2 className="label-wrapper">
<label htmlFor="new-todo-input" className="label__lg">
What needs to be done?
</label>
</h2>
<input
type="text"
id="new-todo-input"
className="input input__lg"
name="text"
autoComplete="off"
value={name}
onChange={handleChange}
/>
<input
type="checkbox"
id="todo-0"
value={important}
onChange={handleChangeImportant}
/> Important
<button type = "submit" className="btn btn__primary btn__lg">
Add
</button>
</form>
);
}
export default Form;
```

Check if name is not empty.
function handleSubmit(e){
e.preventDefault();
//alert('Moin');
if(name !==''){
props.addTask(name);
setName("");
}
}

function handleSubmit(e) {
e.preventDefault();
if (name === '') return;
props.addTask(name);
setName('');
}

Related

How to pass a value in a form OnPost method React

const afterSubmission = (e, message) => {
e.preventDefault()
console.log(message);
if (message === "") return
displayMessage(message)
messageInput.value=""
}
<div id="message-container"></div>
<form onSubmit = {afterSubmission}>
<label for="message-input">Message</label>
<input type="text" id="message-input" />
<button type="submit" id="send-button">Send</button>
</form>
I have these two pieces of code, my question is how can I pass the value from the input tag in the form to the afterSubmission method?
Assuming this is the same component, an easy solution would be to use state.
Your code snippets aren't very useful, just as an FYI for future questions, but here's an example of me tracking form state.
import { useState } from "react";
export default function App() {
const [message, setMessage] = useState("test");
const handleChange = (e) => {
setMessage((old) => e.target.value);
};
const afterSubmission = (e) => {
e.preventDefault();
console.log(message);
};
return (
<div className="App">
<form onSubmit={afterSubmission}>
<input
type="text"
id="message-input"
value={message}
onChange={handleChange}
/>
<button
type="submit"
id="send-button"
>
Send
</button>
</form>
</div>
);
}
As you can see, this tracks your message in the component's state which makes it accessible in the afterSubmission function.

How to Remove the form value After Submit in React from below code?

How can I remove the Input data after submitting the form?
import React from 'react';
import { Form } from 'react-bootstrap';
const AddItem = () => {
const handleItemSubmit = (event) => {
event.preventDefault();
const carName = event.target.carName.value;
const companyName = event.target.companyName.value;
console.log(carName, companyName);
}
return (
<div className='w-50 mx-auto mt-5 py-5 d-block'>
<Form onSubmit={handleItemSubmit}>
<Form.Group className="mb-3" controlId="formBasicCarName">
<Form.Control name="carName" type="text" placeholder="Enter Car Model Name" />
</Form.Group>
<Form.Group className="mb-3" controlId="formBasicCompany">
<Form.Control name="companyName" type="text" placeholder="Enter Company Name" />
</Form.Group>
<button className='btn btn-primary' variant="primary" type="submit">
Submit
</button>
</Form>
</div>
);
};
export default AddItem;
Here I Took two input and get the data by using OnSubmit. Ant I can get the data easily. But I want to reset the value after submit with same button called "submit".
So, In order to remove the reset the form you should use the controlled forms.
By controlled forms i mean using the states to change form inputs. And that's the recommended way and best practice.
so if you'll have to re-write your your code it'll look something like this.
import React ,{useState} from 'react'; // import useState hook
import { Form } from 'react-bootstrap';
const AddItem = () => {
// Initialise Values with empty string or null;
const [inputeVal, setInputVal] = useState({
carName:"",
companyName:"",
});
const handleChange = (event)=>{
const {name, value} = event.target;
setInputVal({...inputVal, [name]:value}) // will set the values from input field to relevant state
}
const handleItemSubmit = () => {
// your handle submit logic goes here
// after submit you can reset the form by resetting the states
setInputVal({
carName:"",
companyName:"",
})
}
return (
<div className='w-50 mx-auto mt-5 py-5 d-block'>
<Form onSubmit={handleItemSubmit}>
<Form.Group className="mb-3" controlId="formBasicCarName">
<Form.Control onChange={handleChange} value={inputVal?.carName} name="carName" type="text" placeholder="Enter Car Model Name" />
</Form.Group>
<Form.Group className="mb-3" controlId="formBasicCompany">
<Form.Control onChange={handleChange} value={inputVal?.companyName} name="companyName" type="text" placeholder="Enter Company Name" />
</Form.Group>
<button className='btn btn-primary' variant="primary" type="submit">
Submit
</button>
</Form>
</div>
);
};
export default AddItem;
reset the form like this:
const handleItemSubmit = (event) => {
event.preventDefault();
const carName = event.target.carName.value;
const companyName = event.target.companyName.value;
console.log(carName, companyName);
event.target.reset(); //add this line
}
Easy fix is to reset the form like this.
const handleItemSubmit = (event) => {
event.preventDefault();
const carName = event.target.carName.value;
const companyName = event.target.companyName.value;
console.log(carName, companyName);
event.target.carName = "";
const inputField = document.getElementById("form");
inputField.reset();
};
And don't forget to Provide the id to your form
<Form onSubmit={handleItemSubmit} id="form">
However, i will highly suggest you to look into callmeizaz answer above about the useState. Thats the proper way to handle form

Prevent form from being refreshing when submitted in Reactjs

Hi I have a Reactjs component in this component .I have a form inside the form i have a search field..when the user hit enter my component reloads.I want to use |prevent defaultso that mycomponentnot reloads when user hitsenter key.How to use in my code`
import React, { useState } from "react";
import data from "./info.json";
function App() {
const [searchTerm, setSearch] = useState(null);
return (
<div>
<form>
<input
type="text"
id=""
placeholder="Search"
onChange={(e) => setSearch(e.target.value)}
/>
</form>
{data
.filter((data) => {
if (searchTerm == null) {
return data;
} else if (
data.name.toLowerCase().includes(searchTerm.toLowerCase())
) {
return data;
}
})
.map((data) => (
<li>{data.name}</li>
))}
</div>
);
}
export default App;
ReactJS supports the onSubmit event by emitting synthetic events for native HTML elements.
For a <form> element, you can use the submit event to prevent the default behavior by using event.preventdefault().
You can do it in two easy steps:
Define an event handler for your form
Use the event handler to prevent form submission
import React, { useState } from "react";
import data from "./info.json";
function App() {
const [searchTerm, setSearch] = useState(null);
const fnHandleSubmit = event => {
event.preventDefault();
}
return (
<div>
<form onSubmit={fnHandleSubmit}>
<input
type="text"
id=""
placeholder="Search"
onChange={(e) => setSearch(e.target.value)}
/>
</form>
{data
.filter((data) => {
if (searchTerm == null) {
return data;
} else if (
data.name.toLowerCase().includes(searchTerm.toLowerCase())
) {
return data;
}
})
.map((data) => (
<li>{data.name}</li>
))}
</div>
);
}
export default App;
Add an onSubmit event handler on the form ,
<form onSubmit={handleOnsubmit}> </form>
in your handleOnsubmit function perfrom event.preventDefault()
function handleOnsubmit(event) {
event.preventDefault();
// Do Whatever you want
}
You will need to add preventDefault() to your form like so:
Add preventDefault() to your onSubmit event of your form:
<form onSubmit={e => e.preventDefault()}>
<input
type="text"
id=""
placeholder="Search"
onChange={e => {
setSearch(e.target.value);
}}
/>
</form>;
When clicked Enter, it triggers onSubmit(), default action is to refresh.
So to onSubmit() add preventDefault to overcome default behaviour.
Add the following line.
<form onSubmit={e => { e.preventDefault(); }}>
//code
</form>
The preventDefault() method cancels the event if it is cancelable, meaning that the default action that belongs to the event will not occur.
For example, this can be useful when:
Clicking on a "Submit" button, prevent it from submitting a form
Clicking on a link, prevent the link from following the URL
const Test = () => {
const submit = (e) => {
e.preventDefault();
console.log('I am here without refresh the form!')
}
return <form onSubmit={submit}>
<input type = 'text' ></input>
</form>
}
ReactDOM.render( <Test/> ,
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>
All you need is to add e.preventDefault();
to your onSubmit function to prevent your component from reloading.
However, I'll advise you to use React UI solutions like Ant Design which provides the feature out of the box and also allow you to write your code more efficiently.

React form refreshing the page despite being told not to

I have a form in a react project that is behaving a bit strange. I have e.preventDefault() attatched to my submit button but for some reason the page is still refreshing each time the button is clicked. Could someone please help me figure out why this is happening? Here is the Component in question:
import React, { useState } from 'react';
import './PostForm.css';
import axios from 'axios'
const PostForm = () => {
const [posts, setPost] = useState({
body: '',
author: 'Michael',
});
const onChange = (e) =>{
setPost({...posts, [e.target.name] : e.target.value})
}
const sendPost = (e) => {
e.preventDefault()
try {
const res = axios.post('http://localhost:4000/post', posts);
console.log(res)
} catch (error) {
console.log(error)
}
}
return (
<form className="formContainer">
<div className="form">
<textarea className='formBody' type="text" placeholder="What's new?" name='body' onChange={onChange} />
<button onSubmit={sendPost}>Share</button>
</div>
</form>
);
};
export default PostForm;
onSubmit should be in the form tag. And change the button to input and it's type as submit.
<form className="formContainer" onSubmit={sendPost}>
<div className="form">
<textarea className='formBody' type="text" placeholder="What's new?" name='body' onChange={onChange} />
<input type="submit" value="Share" />
</div>
</form>

Clear an input field with Reactjs?

I am using a variable below.
var newInput = {
title: this.inputTitle.value,
entry: this.inputEntry.value
};
This is used by my input fields.
<input type="text" id="inputname" className="form-control" ref={el => this.inputTitle = el} />
<textarea id="inputage" ref={el => this.inputEntry = el} className="form-control" />
<button className="btn btn-info" onClick={this.sendthru}>Add</button>
Once I activate {this.sendthru} I want to clear my input fields. However, I am uncertain how to do so.
Also, as shown in this example, it was pointed out to me that I should use the ref property for input values. What I am unclear of is what exactly does it mean to have {el => this.inputEntry = el}. What is the significance of el in this situation?
Let me assume that you have done the 'this' binding of 'sendThru' function.
The below functions clears the input fields when the method is triggered.
sendThru() {
this.inputTitle.value = "";
this.inputEntry.value = "";
}
Refs can be written as inline function expression:
ref={el => this.inputTitle = el}
where el refers to the component.
When refs are written like above, React sees a different function object each time so on every update, ref will be called with null immediately before it's called with the component instance.
Read more about it here.
Declare value attribute for input tag (i.e value= {this.state.name}) and if you want to clear this input value you have to use this.setState({name : ''})
PFB working code for your reference :
<script type="text/babel">
var StateComponent = React.createClass({
resetName : function(event){
this.setState({
name : ''
});
},
render : function(){
return (
<div>
<input type="text" value= {this.state.name}/>
<button onClick={this.resetName}>Reset</button>
</div>
)
}
});
ReactDOM.render(<StateComponent/>, document.getElementById('app'));
</script>
I'm not really sure of the syntax {el => this.inputEntry = el}, but when clearing an input field you assign a ref like you mentioned.
<input type="text" ref="someName" />
Then in the onClick function after you've finished using the input value, just use...
this.refs.someName.value = '';
Edit
Actually the {el => this.inputEntry = el} is the same as this I believe. Maybe someone can correct me. The value for el must be getting passed in from somewhere, to act as the reference.
function (el) {
this.inputEntry = el;
}
I have a similar solution to #Satheesh using React hooks:
State initialization:
const [enteredText, setEnteredText] = useState('');
Input tag:
<input type="text" value={enteredText} (event handler, classNames, etc.) />
Inside the event handler function, after updating the object with data from input form, call:
setEnteredText('');
Note: This is described as 'two-way binding'
You can use input type="reset"
<form action="/action_page.php">
text: <input type="text" name="email" /><br />
<input type="reset" defaultValue="Reset" />
</form>
Now you can use the useRef hook to get some magic if you do not want to use the useState hook:
function MyComponent() {
const inputRef = useRef(null);
const onButtonClick = () => {
// #ts-ignore (us this comment if typescript raises an error)
inputRef.current.value = "";
};
return (
<>
<input ref={inputRef} type="text" />
<button onClick={onButtonClick}>Clear input</button>
</>
);
}
As I mentioned, if you are using useState that is the best way. I wanted to show you also this special approach.
Also after React v 16.8+ you have an ability to use hooks
import React, {useState} from 'react';
const ControlledInputs = () => {
const [firstName, setFirstName] = useState(false);
const handleSubmit = (e) => {
e.preventDefault();
if (firstName) {
console.log('firstName :>> ', firstName);
}
};
return (
<>
<form onSubmit={handleSubmit}>
<label htmlFor="firstName">Name: </label>
<input
type="text"
id="firstName"
name="firstName"
value={firstName}
onChange={(e) => setFirstName(e.target.value)}
/>
<button type="submit">add person</button>
</form>
</>
);
};
You can use useState:
import React, { useState } from 'react';
const [inputTitle, setInputTitle] = useState('');
then add value to your input component:
render() {
<input type="text" onChange={(e) => setInputTitle(e.target.value)}
value={inputTitle} />
<button onClick={handleSubmit} type="submit">Submit</button>
}
On your submit handler function:
setInputTitle('');
document.querySelector('input').defaultValue = '';
On the event of onClick
this.state={
title:''
}
sendthru=()=>{
document.getElementByid('inputname').value = '';
this.setState({
title:''
})
}
<input type="text" id="inputname" className="form-control" ref={el => this.inputTitle = el} />
<button className="btn btn-info" onClick={this.sendthru}>Add</button>
I used the defaultValue property, useRef, and onClick to achieve this.
let ref = useRef()
and then inside the return:
<input type="text" defaultValue="bacon" ref={ref} onClick={() => ref.current.value = ""} />
also if you want to use onChange for the input it wouldn't require any more configuration and you can just use it. If you want to have a dynamic defaultValue then you absolutely can, with useState.
A simple way to reset the input in React is by implementing the onBlur inside the input.
onBlur={cleanSearch}
ej:
const [search, setSearch] = useState('')
const handleSearch = ({target}) =>{
setSearch(target.value)
}
const cleanSearch = () =>setSearch('')
<input
placeholder="Search…"
inputProps={{ 'aria-label': 'search' }}
value={search}
onChange={handleSearch}
onBlur={cleanSearch}
/>
The way I cleared my form input values was to add an id to my form tag.
Then when I handleSubmit I call this.clearForm()
In the clearForm function I then use document.getElementById("myForm").reset();
import React, {Component } from 'react';
import './App.css';
import Button from './components/Button';
import Input from './components/Input';
class App extends Component {
state = {
item: "",
list: []
}
componentDidMount() {
this.clearForm();
}
handleFormSubmit = event => {
this.clearForm()
event.preventDefault()
const item = this.state.item
this.setState ({
list: [...this.state.list, item],
})
}
handleInputChange = event => {
this.setState ({
item: event.target.value
})
}
clearForm = () => {
document.getElementById("myForm").reset();
this.setState({
item: ""
})
}
render() {
return (
<form id="myForm">
<Input
name="textinfo"
onChange={this.handleInputChange}
value={this.state.item}
/>
<Button
onClick={this.handleFormSubmit}
> </Button>
</form>
);
}
}
export default App;

Categories