Onclick to Get Current Date in React js

Onclick to Get Current Date in React js

In this example you can learn how to onclick to get current date in react js. This post will give you example of get current date in react js using react hooks and react built in function. Sometime your require to get current date onclick button. Onclick to get current date using useState hooks and toLocaleDateString.

useState

Read Also :  Get Current Date Month Year in React js

useState to you can update or change data in your functional component in react. useState is a Hook ( method or function ) that allows you to have state variables in functional components. You pass the initial state to this function and it returns a variable with the current state value and another function to update this value.

toLocaleDateString

The toLocaleDateString() function converts the current local date of a Date object into a readable string, using locale conventions.

Read Also :  Onclick to Get Current Time in react js

Example : Onclick to Get Current Date in React js

Index.js

import React, { useState } from 'react'
import ReactDOM from 'react-dom'

function CDate(){
  const dt = null;
  const [cdate,setDate] = useState(dt); 
  const handelDate = () =>{
    let dt = new Date().toLocaleDateString();
    setDate(dt);
  }

  return(
    <>
      <h3>{cdate}</h3>
      <button onClick={handelDate}>Get Current date</button>
    </>
  )
}

ReactDOM.render(<CDate />,document.getElementById("root"));