React clock via props

React clock via props

If you want to create a clock component in React and pass the time through props, there are a few steps to take.

Step 1: Create a Clock Component

Create a new file called Clock.js and import React and PropTypes:


import React from 'react';
import PropTypes from 'prop-types';

class Clock extends React.Component {
  render() {
    return (
      <div>
        {this.props.time}
      </div>
    );
  }
}

Clock.propTypes = {
  time: PropTypes.string.isRequired,
};

export default Clock;

In this example, we have a simple Clock component that takes a time prop and displays it in a div. We also define a prop type for the time prop to make sure it is a string.

Step 2: Pass the Time through Props

Now we can use our Clock component and pass the time through props. Here is an example:


import React from 'react';
import Clock from './Clock';

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      time: new Date().toLocaleTimeString(),
    };
  }

  componentDidMount() {
    setInterval(() => {
      this.setState({
        time: new Date().toLocaleTimeString(),
      });
    }, 1000);
  }

  render() {
    return (
      <div>
        <Clock time={this.state.time} />
      </div>
    );
  }
}

export default App;

In this example, we use the setInterval function to update the time state every second. We then pass the time state through props to our Clock component.

Alternative: Using Functional Component

You can also create a clock component using a functional component instead of a class component:


import React from 'react';
import PropTypes from 'prop-types';

function Clock(props) {
  return (
    <div>
      {props.time}
    </div>
  );
}

Clock.propTypes = {
  time: PropTypes.string.isRequired,
};

export default Clock;

With this method, you don't need to extend the React.Component class. You simply define a function that takes props as an argument and returns JSX.

Conclusion

In this tutorial, we learned how to create a clock component in React and pass the time through props. We also explored an alternative way of creating the clock component using a functional component. Now you can easily add a clock to your React app!

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe