0

I would like to install css modules into create-react-app and I came across this https://github.com/kitze/custom-react-scripts.

After setting things up, I created a test style.module.css file in my folder and import it with import styles from './style.module.css'; like so,

import React, { Component } from 'react';
import styles from './style.module.css';

console.log(styles); //returns '/static/media/style.module.b3708639.css'
console.log(styles.red); //returns 'undefined'

export default class Form extends Component {
    render = () => {
        return (
            <form onSubmit={this.handleSubmit}>
                <TextInput />
                <PasswordInput />
                <Submit />
                <p className={[styles.red, 'test'].join(' ')}>Test</p> //rendered <p class="test">Test</p>
            </form>
        );
    }

    handleSubmit = () => {
        console.log('submit!');
    } 
}

This is my style.module.css content

.facebook_button { margin-top:10px; }
.red { color:red; }

Any advise?

claireckc
  • 395
  • 2
  • 11
  • 1
    CSS can't be printed out using JS like that. Instead, create an html element something like: `

    This should be red

    `
    – PaulProgrammer Apr 06 '18 at 04:00
  • I'm using react from create-react-app with custom-react-scripts fork, trying to use CSS-modules with my components. You are referring to the traditional css html input. Perhaps I should edit my question with code to be more explicit. – claireckc Apr 06 '18 at 04:17
  • Might be trivial to ask, but did you check that you have `REACT_APP_CSS_MODULES=true`? – NTP Apr 06 '18 at 08:32
  • Yeap, i have `REACT_APP_CSS_MODULES = true;` and `REACT_APP_CSS_MODULE_CLASSNAME_TEMPLATE = 'module-[sha512:hash:base32]-[name]-[local]';` – claireckc Apr 06 '18 at 08:49
  • Well, that's perfect and I am trying it right now and I have it displaying perfectly red the Test text. Could it be your // rendered comment is not helping? Try wrapping it with curly braces? – NTP Apr 06 '18 at 08:51
  • Wait, also your class for the Test

    element should be className.

    – NTP Apr 06 '18 at 08:52
  • Oh i added the rendered comment specifically here, its not in my code – claireckc Apr 06 '18 at 08:55
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/168389/discussion-between-ntp-and-claireckc). – NTP Apr 06 '18 at 08:56

1 Answers1

1

Installing the custom-react-scripts as a scripts-version from the beginning should do.

Like this:

create-react-app my-app --scripts-version custom-react-scripts

Otherwise, if installing after using CRA itself on the same app, it will give it the /static/media/ route to static files, which won't give you the styles object you expect in the files where you import it.

NTP
  • 361
  • 1
  • 3
  • 11