javascriptreactjshtml-input

How can I pass a input field value from an exported component in react js


I am not able to get value in an input field from a custom component.

dateFormat.jsx

import React from "react";

const DateFormat = ({ seconds, nanoseconds, format }) => {
  const dates = new Date(seconds * 1000 + nanoseconds / 1000000);
  const day = new Date(dates).toLocaleString("default", { day: "2-digit" });
  const month = new Date(dates).toLocaleString("default", { month: "2-digit" });
  const year = new Date(dates).toLocaleString("default", { year: "numeric" });

  if (format === "dd/mm/yyyy") {
    return <>{day + "/" + month + "/" + year}</>;
  }
  return <>{year + "-" + month + "-" + day}</>;
};

export default DateFormat;

When I call this DateFormat in another page like the example below it works fine

<DateFormat
  nanoseconds={dt.dob.nanoseconds}
  seconds={dt.dob.seconds}
  format={"text"}
/>

The output is like below

12/02/2001

However when I want to get the value in a text field or DatePicker it does not work fine

<input
  type="date"
  className="form-control"
  id="input-datetime-local"
  value={
    <DateFormat
      nanoseconds={dt.dob.nanoseconds}
      seconds={dt.dob.seconds}
      format={"yyyy/mm/dd"}
    />
  }
  onChange={(e) => {
    e.preventDefault();
  }}
  name="dob"
/>

I am expecting an output as below

<input
  type="date"
  className="form-control"
  id="input-datetime-local"
  value="2001/02/12"
  onChange={(e) => {
    e.preventDefault();
  }}
  name="dob"
/>

Solution

  • input element's value prop is typed as

    React.InputHTMLAttributes<HTMLInputElement>.value?: string | number | readonly string[] | undefined
    

    Meaning you can pass a string, string array, number, or undefined as a value. Passing JSX isn't valid.

    I suggest converting DateFormat to a utility function that returns the computed string value.

    const formatDate = ({ seconds, nanoseconds, format }) => {
      const dates = new Date(seconds * 1000 + nanoseconds / 1000000);
      const day = new Date(dates).toLocaleString("default", { day: "2-digit" });
      const month = new Date(dates).toLocaleString("default", { month: "2-digit" });
      const year = new Date(dates).toLocaleString("default", { year: "numeric" });
    
      if (format === "dd/mm/yyyy") {
        return [day, month, year].join("/");
      }
      return [year, month, day].join("-");
    };
    
    export default formatDate;
    
    <input
      type="date"
      className="form-control"
      id="input-datetime-local"
      value={formatDate({
        nanoseconds: dt.dob.nanoseconds,
        seconds: dt.dob.seconds,
        format: "dd/mm/yyyy", // <-- pass correct format for condition test
      })}                     // <-- "02/12/2001" | "2001-02-12"
      onChange={(e) => {
        e.preventDefault();
      }}
      name="dob"
    />