简体   繁体   中英

Show react calendar on click

I'm using react-calendar package on my react app. Placing <Calendar/> on the file gives the open calendar on the frontend.

But I want to display the calendar if the user clicks the input field:

      <div className="form-group">
        <label>Start Date</label>
        <input type="text"/>
        <Calendar style={{display: "none"}} />
      </div>

I tried through inline style to hide the calendar component and change on click. But the calendar doesn't hide with inline css also.

Gone through documentation also but didn't find any help.

It will be best you create a wrapper component around your calendar and input. This way it manages its own showCalendar state and can be reused elsewhere.

import React, { useState } from "react";
import Calendar from "react-calendar";

const ReactCalendarDemo = ({ date, setDate }) => {
  const [showCalendar, setShowCalendar] = useState(false);
  const handleChange = value => {
    setDate(value);
    setShowCalendar(false);
  };

  return (
    <div>
      <input
        value={date.toLocaleDateString()}
        onFocus={() => setShowCalendar(true)}
      />
      <Calendar
        className={showCalendar ? "" : "hide"}
        value={date}
        onChange={handleChange}
      />
    </div>
  );
};

export default ReactCalendarDemo;

You pass in your current date value and its setter as props.

Then you can toggle display in your CSS style using the hide class

.react-calendar.hide {
  display: none;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM