, the issue with your code is that you're trying to mix CSS modules and dynamic styles, but CSS modules don't really work that way. They're more for static, predefined class names. But no worries, there's a simple fix.

You can just use inline styles for dynamic stuff. Inline styles let you plug in your JavaScript values directly into your style attribute.

Here's what you can do:

In your Hero.js, instead of trying to attach your prop to a CSS module class, you can directly use it in a style object. Something like this:

const Hero = ({ heroHeight }) => {
 const dynamicStyle = {
 height: heroHeight, // This is where your dynamic height goes
 border: '1px solid green', // Assuming you always want this green border
};

 return (
  <div className={styles.pageWidth} style={dynamicStyle}>
   {/* Your Hero content */}
  </div>
 );
};

When you use your Hero component, just pass the height like you were doing:

<Hero heroHeight="400px" />
Answer from soheil izadi on Stack Overflow
🌐
Josh W. Comeau
joshwcomeau.com › css › css-variables-for-react-devs
How to use CSS variables with React • Josh W. Comeau
April 13, 2020 - In this tutorial, we're going to see how to take advantage of one of the most exciting newer developments in CSS: CSS variables, AKA Custom Properties. We'll see how we can use them in our React apps to improve our workflows and do some pretty fancy stuff.
Discussions

reactjs - How to use global variables in CSS-Modules? - Stack Overflow
I'm busy learning React with CSS-Modules and I don't quite understand how one would store variables? For example, in Sass you're able to do this: // _variables.scss $primary-color: #f1f1f1; // h... More on stackoverflow.com
🌐 stackoverflow.com
postcss - Update CSS Module variables from Javascript - Stack Overflow
Bring the best of human thought and AI automation together at your work. Explore Stack Internal ... I'm using a (now older) version of react-boilerplate which came with CSS Modules. What's nice about them is that you can create variables and import them in other CSS files. More on stackoverflow.com
🌐 stackoverflow.com
CSS Modules with variable class names
I'm gonna go against the grain here and say these are the kinds of patterns that make going back to a codebase more difficult. Keep it simple (KISS) and just map it function getClassName(level) { if (level === 0) return styles.levelOne; // etc } More on reddit.com
🌐 r/reactjs
9
2
February 19, 2022
sharing variables between css and js
Hi there! There are plenty of issues about importing, but almost all of them somehow refer to JSS, which I ain't fond of. So, the question is simple – can I share variables between js and css, ... More on github.com
🌐 github.com
15
January 19, 2016
🌐
Veera
veerasundar.com › blog › setting-css-variables-from-react
Setting CSS variables from a React app - Blog | Veera
June 19, 2023 - ['marginTop', 'marginBottom'] * @returns a object such as {"--marginTop": "10px", "--marginBottom": "10px"} */ function propsToCSSVariable(props, variableNames) { return variableNames.reduce((acc, key) => { if (props[key] !== undefined) { acc[`--${key}`] = props[key]; } return acc; }, {}); } const cssVariableNames = ["marginTop", "marginBottom"]; function MyCustomButton(props) { return ( <button className={styles.button} style={propsToCSSVariable(props, cssVariableNames)} ></button> ); } With this approach, now I can completely customize my React components with JavaScript and CSS.
🌐
Falldowngoboone
falldowngoboone.com › blog › share-variables-between-javascript-and-css
Share variables between JavaScript and CSS | falldowngoboone
A common variable sharing solution in React is to simply let JavaScript do all the work. And as controversial as CSS-in-JS seems to be, it presents an easy way to share variables simply because you are defining CSS in a JavaScript file.
🌐
Epic React
epicreact.dev › css-variables
Use CSS Variables instead of React Context | Epic React by Kent C. Dodds
July 9, 2024 - With CSS Variables, you can get the values in your CSS with var(--css-variable-name) and in your JavaScript using getComputedStyle(element).getPropertyValue('--css-variable-name') (which you really don't need to do...)
🌐
Reddit
reddit.com › r/reactjs › css modules with variable class names
r/reactjs on Reddit: CSS Modules with variable class names
February 19, 2022 -

Solved

say I have different "level" classes with names like:

level_1
level_2
level_3

and I want to programmatically assign those classes to items that are rendered inside a loop and the items get assigned a level based on a variable. How can I implement this with CSS Modules?

I've tried things like

{`${styles.level_}${itemLevel}`}

and

{"styles.level_".concat(itemLevel)}

but neither works.

To be clear, I need a formula that will result in something like "styles.level_1" when itemLevel === 1, for example.

Find elsewhere
🌐
DEV Community
dev.to › diballesteros › how-to-use-global-mixins-and-variables-with-css-modules-in-react-with-sass-37ie
How to use global mixins and variables with CSS Modules in React with SASS - DEV Community
March 21, 2022 - Create-react-app docs recommend using node-sass for the styling, however, this is deprecated so I would suggest using sass (Dart Sass) as it is still actively receiving support. This can be quickly done with: ... For variables it would be something very similar, let’s have a file with the name _variables.scss:
🌐
GitHub
github.com › css-modules › css-modules › issues › 106
sharing variables between css and js · Issue #106 · css-modules/css-modules
January 19, 2016 - Hi there! There are plenty of issues about importing, but almost all of them somehow refer to JSS, which I ain't fond of. So, the question is simple – can I share variables between js and css, ...
Author   Bloomca
🌐
Atomizedobjects
atomizedobjects.com › blog › react › how-to-use-css-variables-with-react
How to use css variables with React | Atomized Objects
This principle can be used across the entire react application as long as your css with the variables has been imported into the application, this might be worth importing at the root level. Once these variables have been set you can use them in any style across the application, which can be inline-styles, css, css modules, scss, less and so on.
🌐
DEV Community
dev.to › devneagu › how-to-use-css-variables-in-react-component-1a08
[How to] use CSS Variables in React Component - DEV Community
December 9, 2022 - To use CSS variables (also known as "custom properties") in React components, you can define the variables in a separate CSS file, and then use the style attribute in your React components to reference and apply the variables.
🌐
GitHub
github.com › css-modules › css-modules › blob › master › docs › values-variables.md
css-modules/docs/values-variables.md at master · css-modules/css-modules
*/ @value colors: "./colors.css"; @value blue, red, green from colors; .button { color: blue; display: inline-block; } var path = require('path'); var webpack = require('webpack'); var ExtractTextPlugin = require('extract-text-webpack-plugin'); var values = require('postcss-modules-values'); module.exports = { entry: ['./src/index'], output: { filename: 'bundle.js', path: path.join(__dirname, 'public'), publicPath: '/public/', }, module: { loaders: [ { test: /\.js$/, loader: 'babel-loader', exclude: /node_modules/ }, { test: /\.css$/, loader: ExtractTextPlugin.extract( 'style-loader', 'css-loader?modules&importLoaders=1&localIdentName=[name]__[local]___[hash:base64:5]!postcss-loader' ), }, ], }, postcss: [values], plugins: [new ExtractTextPlugin('style.css', { allChunks: true })], };
Author   css-modules
Top answer
1 of 2
15

I usually just define the style as an arrow function that returns the style object, and pass in whatever parameters are needed for the style. There is a shorthand notation for returning an object literal from an arrow function that works nicely for this.

const style = () => ({});

Just remember to only use ternary operators if using the shorthand, otherwise you would just need to explicitly return an object.

So, for your style:

const dropzoneStyle = (isPreview) => ({
  width: `200px`,
  height: `200px`,
  backgroundColor: `#1DA1F2`,
  backgroundImage: (isPreview) ? 'url(/path/to/image.jpg)' : 'none',
});

This adds the image is isPreview is true, but keeps it blank if not.

Then in your component, call the function where the style goes:

return (
  <div>
    <Dropzone
      {...otherProps}
      style={ dropzoneStyle(isPreview) }
    >
  </div>
);
2 of 2
9

Assuming files[0].preview returns a file (image) URL, you should be able to set a new style and pass it to the Dropzone component.

Something along these lines:

const renderDropzoneInput = (field) => {
  const files = field.input.value;
  let dropzoneRef;

  render() {
    let dropzoneStyle = {
      width: `200px`,
      height: `200px`,
      backgroundColor: `#1DA1F2`,
    };

    if (files[0]) {
      dropzoneStyle = {
        width: `200px`,
        height: `200px`,
        backgroundColor: `#1DA1F2`,
        backgroundImage: `url(${files[0].preview})`,
        // or to use a fixed background image
        // backgroundImage: `url(/path/to/static/preview.png)`,
        backgroundPosition: `center center`,
        backgroundRepeat: `no-repeat`
      };
    }

    return (
      <Dropzone
        name={field.name}
        ref={(node) => { dropzoneRef = node; }}
        accept="image/jpeg, image/png"
        style={dropzoneStyle}
      />
    )
  }
}  

a spread operator could be used to DRY this code a bit, with:

let dropzoneStyle = {
  width: `200px`,
  height: `200px`,
  backgroundColor: `#1DA1F2`,
};

if (files[0]) {
  dropzoneStyle = {
    ...dropzoneStyle,
    backgroundImage: `url(/path/to/static/preview.png)`,
    backgroundPosition: `center center`,
    backgroundRepeat: `no-repeat`
  };
}
🌐
Reddit
reddit.com › r/reactjs › is it possible to pass props to css without using styled-components?
r/reactjs on Reddit: Is it possible to pass props to CSS without using styled-components?
December 21, 2022 -

With styled-components we can do something like:
```

const ContactButton = styled.button`   
    background: ${props => props.caseStudyColor};   
    color: #fff;
    font-size: 2rem;   
    padding: 10px; 
`;     

<ContactButton caseStudyColor={'#004655'} /> 

```

This can be pretty useful for maybe passing unique styles based on a condition to a component we return from a map function or something similar, but my question is, is there any way to do this without the use of styled-components???

🌐
GitHub
github.com › css-modules › css-modules › issues › 86
Access SASS variables from css-module in a React component · Issue #86 · css-modules/css-modules
November 20, 2015 - import styles from './styles'; import React from 'react'; import SomeFooBarComponent from 'irrelevant'; export default class MyComponent extends React.Component { render() { return ( <div className={styles.root}> <h1>My amazing page</h1> {/* I want to use a variable here, rather than hard-code the color. I want that variable to come from my imported styles file (i.e.
Author   hdmchl