2

I'm new to building stuff in React and am trying to put together a component that will style itself but that can optionally be styled by the calling context. So I have something like this:

/*eslint-disable*/
import React from "react";
import PropTypes from "prop-types";
import classNames from "classnames";

import styles from "./style.js";

function Section(props) {
    const { style } = props;
    if (style) import styles from style; // unhappiness here
    const classes = styles();
    const sectionClasses = classNames({
        [classes.section]: true
    });
    return (
        <div className={sectionClasses}>
            {props.children}
        </div>
    )
}

Section.propTypes = {
  style: PropTypes.string
}

export default Section

but, of course, import isn't happy being manhandled like that (see: How can I conditionally import an ES6 module?). I would like to just use require() but I have a feeling the webpacking will suffer

so how is this typically implemented?

ekkis
  • 9,804
  • 13
  • 55
  • 105
  • 1
    You could create an empty functional component that has the import in it's file and conditionally render that. Just my two cents. – Rodrigo Apr 20 '20 at 00:13
  • 1
    "I would like to just use require() but I have a feeling the webpacking will suffer". did you try it? if so, what specifically went wrong? if not, why not? – Dan O Apr 20 '20 at 00:18

1 Answers1

-1

Do you really need conditional imports? This might be a better approach:

import styles1 from "./style1.js";
import styles2 from "./style2.js";

// or import { styles1, styles2 } from "./style.js";

...

function Section(props) {
    const { style } = props;
    let styles;
    if (style) styles = style1;
    else styles = style2;

    ...
}
Adrian Carolli
  • 695
  • 6
  • 21