10-0Formulario Minimalista con React (Solo Nombre)

 

Formulario Minimalista con React (Solo Nombre)

jsx
Copy
Download
import { useState } from 'react';

function SimpleForm() {
  const [nombre, setNombre] = useState('');
  const [mensaje, setMensaje] = useState('');

  const handleSubmit = (e) => {
    e.preventDefault();
    if (!nombre.trim()) {
      setMensaje('Por favor ingresa tu nombre');
      return;
    }
    setMensaje(`¡Hola ${nombre}! Formulario enviado correctamente.`);
    setNombre(''); // Limpia el campo después del envío
  };

  return (
    <div style={{ maxWidth: '300px', margin: '20px auto' }}>
      <h2>Formulario Simple</h2>
      <form onSubmit={handleSubmit}>
        <div style={{ marginBottom: '10px' }}>
          <label>
            Tu nombre:
            <input
              type="text"
              value={nombre}
              onChange={(e) => setNombre(e.target.value)}
              style={{ marginLeft: '10px', padding: '5px' }}
            />
          </label>
        </div>
        <button 
          type="submit"
          style={{ padding: '5px 15px', cursor: 'pointer' }}
        >
          Enviar
        </button>
      </form>
      {mensaje && <p style={{ marginTop: '10px' }}>{mensaje}</p>}
    </div>
  );
}

export default SimpleForm;

Características clave:

  1. Estado mínimo:

    • Solo nombre para almacenar el valor del input

    • mensaje para mostrar retroalimentación

  2. Validación básica:

    • Verifica que el nombre no esté vacío (.trim() elimina espacios en blanco)

  3. Comportamiento:

    • Muestra mensaje de éxito/error

    • Limpia el campo después del envío exitoso

    • Diseño minimalista con estilos en línea

  4. Mejoras posibles:

    • Agregar manejo de envío a API

    • Incluir estado de carga

    • Añadir más validaciones

Versión aún más minimalista (sin mensajes):

jsx
Copy
Download
import { useState } from 'react';

function MinimalForm() {
  const [nombre, setNombre] = useState('');

  const handleSubmit = (e) => {
    e.preventDefault();
    alert(`¡Hola ${nombre}!`);
    setNombre('');
  };

  return (
    <form onSubmit={handleSubmit}>
      <input
        type="text"
        value={nombre}
        onChange={(e) => setNombre(e.target.value)}
        placeholder="Tu nombre"
      />
      <button type="submit">Saludar</button>
    </form>
  );
}

Comentarios

Entradas más populares de este blog

10-2-formulario

10-3-Formulario