can I "import" React CSS modules from a string?

Viewed 780

I have a React project that uses CSS Modules by importing .css files. e.g. import styles from "./styles/MyComponent.css";

I find myself now in a situation where a component is receiving a customized snippet of CSS as a string in response to a dynamic call to the server.

Is it possible to take this string (which is unknown until runtime) and essentially do the same thing to it that import does to the .css file when it is compiled by webpack?

For example:

import styles from "./styles/MyComponent.css";

//later on in component...
moreStyle = "a string containing valid CSS";

//do *something* here to moreStyle string to do whatever importing does to a file.

myJSX = (
  <div className={styles.someClass}>
    This div content is styled by someClass
  </div>
  <div className={moreStyle.someOtherClass}>
    This div content needs to be styled by someOtherClass, but obviously this isn't working
  </div>
);
1 Answers

You can try this:

import styles from "./styles/MyComponent.js";

myJSX = (
  <div style={styles.someClass}>
    This div content is styled by someClass
  </div>
  <div style={styles.someOtherClass}>
    This div content needs to be styled by someOtherClass, but obviously this isn't working
  </div>
);

Consider creating a serialized object, instead.

// Filename: MyComponentStyle.js
//Example styles
export const styles = {
  someClass: { height: 10 },
  someOtherClass: {
    backgroundColor: 'red',
  }
};

React doesn't work like your typical HTML/CSS/JS app. The thing to note that JSX may look like HTML but it is not HTML.

In your code, className is being defined as a string, which is expected, however, there's possibly no CSS being referred to in this document. Try to console.log it and see what you get.

...

Another possible solution is to simply have your style within the same component file. A common design choice for component styling is inline styling. This is especially useful for projects of medium-large scale, where managing files can get difficult.

Helpful references:

https://reactjs.org/docs/dom-elements.html#style

https://codeburst.io/4-four-ways-to-style-react-components-ac6f323da822

Related