How can I change a route in my reactJs menu.js component from 1 route to another depending on a timestamp. For example, when it's the 1st of Decembre the following will change:
From:
<Link to="/coming-soon">Coming Soon</Link>
To:
<Link to="/store">Store</Link>
I am using a functional component for the menu.js , and I don't have much experience in ReactJs
UPDATE: App.js
return (
<>
<Menu />
<Switch>
<Route path="/" exact>
<LandingPage />
</Route>
<Route path="/coming-soon" exact>
<ComingSoon />
</Route>
<Route path="/store" exact>
<Store />
</Route>
</Switch>
<Footer />
</>
);
CodePudding user response:
You can set route path dynamically when you get timestamp changed, at that time you can use like below
<Link to="/${yourdynamicpath}">{Title}</Link>
CodePudding user response:
Edit: I notice you want to add a check to update it without refreshing, so I'd adjust the functional component to store the first date in a const [currentDate, setCurrentDate] = useState(new Date())
and within the useEffect update that with an interval e.g.:
useEffect(() => {
const interval = setInterval(() => {
setCurrentDate(new Date())
}, 1000); // set this as you wish on how responsive you wish it to be
return () => clearInterval(interval);
}, []);
Depending if you already have a date formatting library installed the exact implementation could differ, but for example if you use date-fns you are provided lots of helpful utils like:
compareAsc(dateLeft, dateRight)
which can be used like so to compare dates, we compare todays date new Date()
to december 1st new Date('1/12/2021')
, if the first date is before the second date it returns -1, so the condition is true and we show the coming soon, if its after we return 1, the condition is false and then we show the store:
return (
<>
<Menu />
<Switch>
<Route path="/" exact>
<LandingPage />
</Route>
</Switch>
{compareAsc(currentDate, new Date("1/12/2021")) === -1 ? (
<Route path="/coming-soon" exact>
<ComingSoon />
</Route>
) : (
<Route path="/store" exact>
<Store />
</Route>
)}
<Footer />
</>
)
Not that it's necessarily recommended to pull a package for everything - but for dates these provide lots of handy utils so getting used to all that they have to offer can be useful if you haven't seen them yet!