Extelliqent
Extelliqent

Reputation: 1860

React Passing Const Function Around

I am calculating time in App.js and passing it to the child to just display. I know none of this makes sense, but I am practicing learning how to create const and send over to child then accept from child and print on the page. This example works but I assume there is a better way to do this than what I did here, isn't it?

App.js

const Time = () => {
  const dateBirth = moment('19010522', 'YYYYMMDD')
  const dateNow = moment()
  const difference = dateNow.diff(dateBirth, "years")
  return (
    <div>{difference}</div>
  )
}

class App extends Component {
  render() {
    const date = <Time />;
    return (
      <div>
        <Person Time={date} />
      </div>
    );
  }
}

export default App;

Person.js

export default function Person({ Time }) {
  return (
    <span>
        Time: {Time}
    </span>
  )
}

Also I tried to send it like below, it didn't work. Why?

<Person Time={Time} />

Upvotes: 0

Views: 56

Answers (1)

Blue
Blue

Reputation: 22911

If you're doing it by using <Person Time={Time} />, then your person component should look like this:

export default function Person({ Time }) {
  return (
    <span>
        Time: <Time />
    </span>
  )
}

Upvotes: 2

Related Questions