简体   繁体   中英

Importing css in JSX file

I am trying to import css styles into js file, but i cannot use styles properly

in my file Graph.js :

import React from 'react';
import styles from './Graph.css';
import Center from './Center/Center'

class Graph extends React.Component {

    render(){
        return(
            <div className={styles.graph}>
                <Center>test</Center>
            </div>
        );
    }
}

export default Graph;

I try to use style from file Graph.css which looks like this:

.graph {
    height: 500px;
    width: 500px;
    border: 1px solid grey;
}

Is there a possibility to manage importing styles to components this way?

your import statement should be import './Graph.css'; and in component <div className="graph">

You are probably confusing react and react-native.

In react, you don't need to styles.graph .

Rather doing the way you do it in normal .html file would work

import React from 'react';
import styles from './Graph.css';
import Center from './Center/Center'

class Graph extends React.Component {
    render() {
        return (
            <div className="graph"
                <Center>test</Center>
            </div >
        );
    }
}

export default Graph;

You are missing an important css rule option in your webpack config.

{
    loader: 'css-loader',
    options: {
        modules: true,
        camelCase: true
    }
}

Add this options object in order to import styles. The modules option let you enable to use your css as a style object and camelCase option enables using "some-class" as someClass.

Hope this will help.

You need to import file directly ie import './Graph.css' and use it as normal class on div or whenever you want. There are other ways to stlye element such as inline style and more. You can explore more here . https://codeburst.io/4-four-ways-to-style-react-components-ac6f323da822 (its great article)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM