maryannt
maryannt

Reputation: 41

How do i display different times with React/JSX?

I am having trouble rendering a time for different countries using JSX without hardcoding the return value as seen in my code below. I tried passing it through the Date.now but it did not work. I want to do it for three random countries. How exactly would i structure it?

Here is my current code

<html>
 <head>
   <!-- we need to specify the react framework here -->
   <script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
   <script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
   <script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>
 </head>
<body>
<div id="root"></div>
<script type="text/babel">



function Clock(props, city) {
  return <h1>The time is {props.date.toLocaleTimeString({timeZone:'Europe/London'})}</h1>
}


function tick () {
  ReactDOM.render(
    <Clock date={new Date()}/>,
    document.getElementById('root')
  )
}
setInterval(tick, 1000)


</script>
</body>
</html>

Upvotes: 2

Views: 61

Answers (1)

Tu Nguyen
Tu Nguyen

Reputation: 10179

Try this

<html>
 <head>
   <!-- we need to specify the react framework here -->
   <script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
   <script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
   <script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>
 </head>
<body>
<div id="root"></div>
<script type="text/babel">

function Clock(props) {
  return <h1>The time is {props.date.toLocaleTimeString({timeZone:props.city})}</h1>
}

function tick () {
  ReactDOM.render(
    <Clock date={new Date()} city='Europe/London'/>,
    document.getElementById('root')
  )
}
setInterval(tick, 1000)
</script>
</body>
</html>

The reason is, according to React Document - Rendering a Component:

When React sees an element representing a user-defined component, it passes JSX attributes to this component as a single object. We call this object “props”.

In other words, all of JSX attributes that you passed to the component will be contained inside the props object.

Upvotes: 1

Related Questions