Steven
Steven

Reputation: 19425

How do I import React component based on a dependancy?

I'm using React (babel) and jsx for the first time and Webpack for creating my bundle.js

I've crated two React components - Header1.jsx and Header2.jsx.

If before 4.July 2016 -> use Header1.jsx
If after 4.July 2016 -> use Header2.jsx

To import the components into React I'm using index.js:

import SportMenu from './components/SportMenu.jsx';
import NextMatches from './components/NextMatches.jsx';
(...)

Basically I want a code that does this:

var eventStart = new Date('2016-06-10T21:00:00+02:00');
var now = new Date();

if(nowgetDate().getDate() < eventStart.getDate()){
    import EmCountdown from './components/Countdown.jsx';
} else {
    import FocusMenu from './components/FocusMenu.jsx';
}

How can I accomplish this?

Upvotes: 1

Views: 79

Answers (1)

Oleksandr T.
Oleksandr T.

Reputation: 77482

You can't import modules dynamically, however you can import them as usual modules

import SportMenu from './components/SportMenu.jsx'; 
import NextMatches from './components/NextMatches.jsx'; 
import EmCountdown from './components/Countdown.jsx'; 
import FocusMenu from './components/FocusMenu.jsx'; 

and then render them by condition

var eventStart = new Date('2016-06-10T21:00:00+02:00');
var now = new Date();

if (now < eventStart){
    <EmCountdown />; 
} else {
    <FocusMenu />;
}

Upvotes: 3

Related Questions