1

I have a component in React like this:

const myAge = () => {
  var diff = Date.now() - new Date(1991, 2, 1);
  var age = new Date(diff);
  return age;
};
export const About = (props) => {
  return (
      <Container id={props.id}>
         <p> My age is: {myAge}</p>
      </Container>
  )
}

I want the result of the function myAge to be returned and rendered in the p tag, but nothing is rendered. I don't know what I'm doing wrong, any suggestions? Ty.

4
  • 2
    You have to call myAge, like this {myAge()} Commented Apr 11, 2021 at 21:58
  • I tryied that but this error happend: Error: Objects are not valid as a React child (found: Mon Jul 24 1995 16:02:22 GMT-0300 (hora estándar de Arg)). If you meant to render a collection of children, use an array instead. Commented Apr 11, 2021 at 22:03
  • React expects a string, and a Date is not a string, you can cast it by saying return String(age) or another way if you want to format it some specific way Commented Apr 11, 2021 at 22:04
  • 1
    Yes that work, if u want answer and I give the best answer Commented Apr 11, 2021 at 22:05

1 Answer 1

3

You have to call the function, that is {myAge()} and then the new Date(diff) is not a string, so you have to cast it like this return String(age)

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.