简体   繁体   中英

How to prevent adding empty task in react code?

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(''); }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM