Forms in React.js - Writing and Managing Forms

Qorista iyo Maareynta Foomamka ee React.js

Foomamku waa qayb muhiim ah oo ka mid ah bogagga websaydhka, maadaama ay dadka u oggolaanayaan inay geliyaan xog loona gudbiyo backend-ka. React.js waxa ay leedahay habab kala duwan oo lagu maareeyo foomamka, taas oo ka dhigaysa wax ka qabashadooda mid fudud oo la maamuli karo.

forms in react js
forms in react js


Isticmaalka State si loo Maareeyo Foomamka

Marka foom lagu qoro React, waa muhiim in la xakameeyo xogta la gelinayo. Sida caadiga ah, waxaa la isticmaalayaa useState si loo maareeyo xogta foomka.

import { useState } from "react";

function ContactForm() {
  const [name, setName] = useState("");
  const [email, setEmail] = useState("");

  const handleSubmit = (e) => {
    e.preventDefault();
    console.log("Magaca:", name, "Email:", email);
  };

  return (
    <form onSubmit={handleSubmit}>
      <label>Magaca:</label>
      <input
        type="text"
        value={name}
        onChange={(e) => setName(e.target.value)}
      />
      <label>Email:</label>
      <input
        type="email"
        value={email}
        onChange={(e) => setEmail(e.target.value)}
      />
      <button type="submit">Gudbi</button>
    </form>
  );
}
export default ContactForm;

Foomamka Aan La Xakameynin (Uncontrolled Forms)

Marka aan rabno inaan isticmaalno foom aan la xakameynin, waxaan isticmaalnaa ref halkii aan ka isticmaali lahayn useState.

forms in react js
forms in react js


import { useRef } from "react";

function UncontrolledForm() {
  const nameRef = useRef();
  const emailRef = useRef();

  const handleSubmit = (e) => {
    e.preventDefault();
    console.log("Magaca:", nameRef.current.value, "Email:", emailRef.current.value);
  };

  return (
    <form onSubmit={handleSubmit}>
      <label>Magaca:</label>
      <input type="text" ref={nameRef} />
      <label>Email:</label>
      <input type="email" ref={emailRef} />
      <button type="submit">Gudbi</button>
    </form>
  );
}
export default UncontrolledForm;

Xaqiijinta Xogta (Validation)

Si loo hubiyo in xogta foomka sax tahay, waxaan isticmaali karnaa useState iyo shuruudo lagu xakameeyo xogta la gelinayo.

const handleSubmit = (e) => {
  e.preventDefault();
  if (!name || !email.includes("@")) {
    alert("Fadlan geli xog sax ah.");
    return;
  }
  console.log("Xogta waa la gudbiyay");
};

Gabagabo

Foomamka React waxa ay la yimaadeen laba hab oo loo maareeyo: controlled iyo uncontrolled. Waxaa lagu xakameyn karaa useState, useRef, iyo xaqiijin si looga fogaado khaladaadka. Habka saxda ah ee aad u doorato waxay ku xiran tahay baahida mashruucaaga. React waxa ay ka dhigaysaa foomamka kuwo fudud oo si sahlan loo maamuli karo.

Previous Post Next Post

Important

Important