I am building a calendar, it has 53 weeks from (12-30-2019 -> 03-01-2021). How when the app first loads it display current date.
// the function display dates
export default function RenderDates(props) {
const dates_ = [];
const startDate = moment('12-29-2019', 'MM-DD-YYYY');
// display date in week
for(let i = 1; i <= 53*7; i++) {
dates_.push(
<Date>
<ContentDate>
<ShortDate>{moment.weekdaysShort()[i%7]}</ShortDate>
<span>{startDate.add(1,'days').get('Date')}</span>
</ContentDate>
</Date>
)
}
return dates_;
}
demo: https://codesandbox.io/s/github/Kalipts/scroll_calendar?file=/src/components/RenderDates.js
You can assign unique id to every date box and then focus today's box
https://codesandbox.io/s/quirky-leavitt-w2x3w
export default function RenderDates(props) { const dates_ = []; const startDate = moment("12-29-2019", "MM-DD-YYYY"); useEffect(() => { const today = moment().format("YYYY-MM-DD"); console.log('today', today); const node = document.getElementById(today); if (node) { node.setAttribute("tabindex", "-1"); node.focus(); node.removeAttribute("tabindex"); } }, []); for (let i = 1; i <= 53 * 7; i++) { const date = startDate.add(1, "days"); dates_.push( <Date id={date.format("YYYY-MM-DD")}> <ContentDate> <ShortDate>{moment.weekdaysShort()[i % 7]}</ShortDate> <span>{date.get("Date")}</span> </ContentDate> </Date> ); } return dates_; }
I just changed a bit your codesandbox to make it work and here is the link: https://codesandbox.io/s/vibrant-worker-b2xhq?file=/src/App.js
Basically what I did was:
RenderDates
component I check for the current date and added an id to the Date component if that date was the current one.App
component (It could be on RenderDates component) I added a useEffect
to run once the component is mounted that getElementById
using the id on date and scrollIntoView
.It is very simple and works well: :)
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.