Search code examples
cssreactjsenvironment-variablescreate-react-app

How to use environment variables in ReactJS imported CSS?


I created a simple React app using https://github.com/facebookincubator/create-react-app.

I am trying to specify a configurable URL to a component's CSS like this:

.Cell {
    background-image: url({process.env.REACT_APP_STATIC_URL}./someImage.png);
}

And here's the component:

import React from 'react';
import './Cell.css'

class Cell extends React.Component {
    render() {
        return (
            <div className="Cell">
                {this.props.name}
            </div>
        );
    }
}

But it doesn't look like the process variable trickles down to the imported CSS. How would I go about doing this?


Solution

  • If you want to use js variables in CSS, try React inline-style instead of plain css file.

    https://facebook.github.io/react/tips/inline-styles.html

    If you want to separate CSS and JS, you might need a CSS preprocessor to manage your global variables.