2

How can we define CSS class within react component, not in external style sheet? I know there is a concept call CSS module which solve the issue of global style sheet. Is there any other way to style component by defining classes with in component?

T J
  • 42,762
  • 13
  • 83
  • 138
osama
  • 116
  • 1
  • 9
  • `className="theclass"`? – Keith Jul 20 '18 at 15:36
  • no i know i can apply class with className="theclass". but i am asking can i define theclass within component – osama Jul 20 '18 at 15:37
  • As you can define styles as objects and pass them via the `style` property. But this is limited to a subset of css. A solution fully supporting all features of css is e.g. [styled components](https://www.styled-components.com/). – trixn Jul 20 '18 at 15:39
  • You can apply style directly, eg. `style={style}` `const style={backgroundColor: green};` But personally I think this is not ideal, I use less and then do something like `.myclass-button { /*style here*/ }` and then of course do -> `
    ...`
    – Keith Jul 20 '18 at 15:39
  • Depending on your webpack config, you can import your CSS file as `import 'myfile.css'`. If you use create-react-app, that comes out of the box. – mccambridge Jul 20 '18 at 15:41
  • Possible duplicate of [How to apply CSS and Styling to a React component](https://stackoverflow.com/questions/38545219/how-to-apply-css-and-styling-to-a-react-component) – hcs Jul 20 '18 at 15:45

1 Answers1

0

enter image description hereit's very simple, just run command "npm run eject" It moves create-react-app’s configuration files and dev/build/test scripts into you app directory.

now go to config folder and open 'webPackConfig.js' file and add the following code

          use: getStyleLoaders({
              ....
              ....
            modules:true,
            getLocalIdent:getCSSModuleLocalIdent,
            localIdentName: '[name]_[local]_[hash:base64:5]'
          })

example:

import React from 'xyz';
import Logo from '../../Logo/Logo';

import classes from './Toolbar.css';
import NavigationItems from '../NavigationItems/NavigationItems';
import DrawerToggle from '../SideDrawer/DrawerToggle/DrawerToggle';

const toolbar = (props) => (
    <header className={classes.Toolbar}>
        <DrawerToggle clicked={props.DrawerToggleClicked}/>
        <div className={classes.Logo}>
            <Logo />
        </div>
        <nav className={classes.DesktopOnly}>
            <NavigationItems />
        </nav>
    </header>
);
export default toolbar;

try this and you can definitely solve your issue

Fazal
  • 99
  • 1
  • 6