Home > Software engineering >  Functional Component to display input fields
Functional Component to display input fields

Time:05-27

I have a simple form in react JS. I would like users to have an option to choose between Phone Number or Email Address based on preference.

For Example:

<form >
  <label  for="inlineFormCustomSelectPref">
   How should we contact you ?? 
  </label>
   <select  id="inlineFormCustomSelectPref">
    <option selected>Choose...</option>
    <option value="1">Phone Number</option>
    <option value="2">Email</option>
   </select>
</form>

I would like to display either of these below fields:

  <input onChange={(event) => setPhone(event.target.value)} /> // <-- display this if a user choose Phone

  <input onChange={(event) => setEmail(event.target.value)} /> // <-- display this if a user choose Email

This is currently how I have written the code, I intend to fill the form and use that data when the handleSubmit takes place.

import React, { useState } from "react";

function Checkout({ cart }) {
  let textInput = React.createRef();

  function handleClick() {
    console.log(textInput.current.value);
  }

  const [title, setName] = useState("");
  const [contactPreference, setContactPreference] = useState("");
  const [phone, setPhone] = useState("");
  const [email, setEmail] = useState("");

  const handleSubmit = () => {
    const token = "fb83b937-2739-3d6e-9519-09387b92dfae";
    const data = {
      transactionReference: "string",
      paymentMethod: "CreditCard",
      checkoutOrderUrl: "http://www.test.com/",
      user: {
        name: "", // this is where the name from input field needs to be used
        msisdn: " 27610983142", // this is where the phone number from input field needs to be used
        email: "[email protected]", // this is where the email from input field needs to be used
      },
      payementMethodDetail: {
        RedirectUrl: "http://www.test.com",
        PurchaseEventWebhookUrl: "http://www.test.com",
      },

      bundle: cart.map((item) => ({
        ProductCode: `${item.ProductCode}`,
        Amount: item.amount,
        CurrencyCode: item.currencyCode,
        Quantity: item.quantity,
      })),
    };
    const requestOptions = {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        Authorization: `Bearer ${token}`,
      },
      body: JSON.stringify(data),
    };
    fetch(
      "https://api.flash-internal.flash-group.com/ecommerceManagement/1.0.0/api/checkout/",
      requestOptions
    )
      .then((response) => response.json())
      .then((res) => console.log(res));
  };

  return (
    <div className="App">
      <button type="submit" onClick={handleSubmit}>
        Post items
      </button>
      <div>
        Name: <input onChange={(event) => setName(event.target.value)} />
        <form >
          <label  for="inlineFormCustomSelectPref">
            How should we contact you ??
          </label>
          <select
            onChange={(e) => {
              setContactPreference(e.target.value);
            }}
            
            id="inlineFormCustomSelectPref"
          >
            <option selected>Choose...</option>
            <option value="phone">Phone Number</option>
            <option value="email">Email</option>
          </select>
          {contactPreference === "phone" ? (
            <input
              placeholder="Enter your phone number."
              onChange={(event) => setPhone(event.target.value)}
            />
          ) : contactPreference === "email" ? (
            <input
              placeholder="Enter your email address."
              onChange={(event) => setEmail(event.target.value)}
            />
          ) : (
            <></>
          )}
        </form>
      </div>
    </div>
  );
}

export default Checkout;

CodePudding user response:

Here you go, just store their preference option in state and then display the corresponding input field.

    const [contactPreference, setContactPreference] = useState("");
    const [phone, setPhone] = useState("");
    const [email, setEmail] = useState("");
    return (
        <div>
            <form >
                <label  for="inlineFormCustomSelectPref">
                    How should we contact you ??
                </label>
                <select
                    onChange={(e) => {
                        setContactPreference(e.target.value);
                    }}
                    
                    id="inlineFormCustomSelectPref"
                >
                    <option selected>Choose...</option>
                    <option value="phone">Phone Number</option>
                    <option value="email">Email</option>
                </select>
                {contactPreference === "phone" ? (
                    <input
                        placeholder="Enter your phone number."
                        onChange={(event) => setPhone(event.target.value)}
                    />
                ) : contactPreference === "email" ? (
                    <input
                        placeholder="Enter your email address."
                        onChange={(event) => setEmail(event.target.value)}
                    />
                ) : (
                    <></>
                )}
            </form>
        </div>
    );

Use the collected data in a POST request by changing the following:

    user: {
                name: name, // remember to change the useState declaration
                msisdn: phone, 
                email: email, 
            },

You should change

    const [title, setName] = useState("");

to

    const [name, setName] = useState("");
  • Related