Así que tengo un formulario de envío donde el usuario necesita crear una tarea escribiendo un nombre de tarea. Quiero que esté vacío al principio y tenga un marcador de posición de "debe ingresar una tarea" cuando el usuario haga clic en agregar sin ingresar nada. Ahora puedo lograr que muestre el marcador de posición, pero siempre está ahí o me encuentro con un código inalcanzable. Sé cómo limpiar el envío y volver a la función de agregar, solo necesito poder mostrar el marcador de posición de forma condicional. Así es como se ve mi código atm:
import { useState } from "react"; export default function Todos() { const [todos, setTodos] = useState([{ text: "hey" }]); const [todoText, setTodoText] = useState(""); const [isEmpty, setEmpty] = useState("false"); const addTodo = (e) => { e.preventDefault(); if (todoText){ setTodos([...todos, { text: todoText }]); setTodoText(""); } else { setEmpty(true) setTodoText(""); return } } return ( <div> {todos.map((todo, index) => ( <div key={index}> <input type="checkbox" /> <label>{todo.text}</label> </div> ))} <br /> <form onSubmit={addTodo}> <input value={todoText} onChange={(e) => setTodoText(e.target.value)} type="text" ></input> <button type="submit">Add</button> {isEmpty &&<span style={{ color: "red" }}>Enter a task</span>} </form> </div> ); }Podría cambiar tu código con lo siguiente:
Debe inicializar isEmpty por false en lugar de string "false" .
Y puede usar esta bandera para mostrar textos de marcador de posición.
Tenga en cuenta que cambié el nombre de isEmpty por showError .
import { useState } from "react"; export default function Todos() { const [todos, setTodos] = useState([{text: "hey"}]); const [todoText, setTodoText] = useState(""); const [showError, setShowError] = useState(false); // @ts-ignore const addTodo = (e) => { e.preventDefault(); if (todoText) { setTodos([...todos, {text: todoText}]); setTodoText(""); setShowError(false); } else { setTodoText(""); setShowError(true); return } } return ( <div> {todos.map((todo, index) => ( <div key={index}> <input type="checkbox"/> <label>{todo.text}</label> </div> ))} <br/> <form onSubmit={addTodo}> <input value={todoText} onChange={(e) => setTodoText(e.target.value)} type="text" ></input> <button type="submit">Add</button> {(showError && !todoText) && <span style={{color: "red"}}>Enter a task</span>} </form> </div> ); }