Home > Back-end >  TypeError: Date.getFullYear is not a function on ReactJs
TypeError: Date.getFullYear is not a function on ReactJs

Time:12-06

I am trying to add a dynamic list to my Expanse List and am getting this error while doing it:

**TypeError: Date.getFullYear is not a function**

[TypeError: Date.getFullYear is not a function on ReactJs ][1]

but in a static list, it shows me the format as I wanted with no error.

This is a static list

I am trying to update the list depending on user input.

Expanse.js

  return (
    <div>
      <Wrapper>
        <DateAndTitle>
          <ExpanseTime>
            <ExpanseDates Date={date} />
          </ExpanseTime>
          <Title>{title}</Title>
        </DateAndTitle>
        <Amount>{amount}$</Amount>
      </Wrapper>
    </div>
  );
};

ExpanseDate.js


  let month =Date.toLocaleString("en-US", { day: "2-digit" });
  let day = Date.toLocaleString("en-US", { month: "long" });
  let year = Date.getFullYear();


  return (
    <Wrapper>
     <ExpanseDays>{day}</ExpanseDays>
      <ExpanseMonth>{month}</ExpanseMonth>
      <ExpanseYear>{year}</ExpanseYear>

    </Wrapper>
  );
};

AddExpanse.js

This is User Input

The is userInput code :

enter image description here

CodePudding user response:

Try this:

const now = new Date();
let month = now.toLocaleString("en-US", { day: "2-digit" });
let day = now.toLocaleString("en-US", { month: "long" });
let year = now.getFullYear();

CodePudding user response:

The example you've shown is incomplete and can't be used to reproduce your error. However, here's a snippet which includes relevant portions in your question, demonstrating how to destructure a value from a component's props:

In the case of your code, the property's name happens to be Date, which is the same name as the builtin Date class in JavaScript and shadows it in the scope of the component. This is generally not a good practice: it's not a good idea to shadow built-ins.

Try renaming that prop in your ExpanseDates component to avoid ambiguity with the builtin Date.

<div id="root"></div><script src="https://unpkg.com/[email protected]/umd/react.development.js"></script><script src="https://unpkg.com/[email protected]/umd/react-dom.development.js"></script><script src="https://unpkg.com/@babel/[email protected]/babel.min.js"></script>
<script type="text/babel" data-type="module" data-presets="react">

function Component (props) {
  const {Date} = props;
  let day = Date.toLocaleString("en-US", { day: "2-digit" });
  let month = Date.toLocaleString("en-US", { month: "long" });
  let year = Date.getFullYear();
  return <div>{year} {month} {day}</div>;
}

function Example () {
  const date = new Date();
  return <Component Date={date} />;
}

ReactDOM.render(<Example />, document.getElementById('root'));

</script>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related