Geeky
Geeky

Reputation: 7496

React and CSS Styling

In my page, I have to use two react components

Component1 and Component2

Page1 code

<Component1/>
<Component2/>

All the styling for components would come from the component CSS files. But for the page layout, I have page1.css

I would write selectors and classnames and define styles for page1.css.

There could be many pages and different layouts with similar classnames, how can we control the behavior of not having overriding styles.

Upvotes: 0

Views: 93

Answers (2)

Tony Bui
Tony Bui

Reputation: 1299

You can use CSS module to apply the style to each component, it works so well, easy to manage code and it is local selector as well, so there is no conflict between 2 component.

Project tree will be like:

Component:

  • Button
    • Button.js
    • Button.module.css
  • Form
    • Form.js
    • Form.module.css
  • Avatar
    • Avatar.js
    • Avatar.module.css

Each component will have a unique css file to come with, so it is very easy to maintain the code when scaling up.

How to use:

  1. create-react-app
  2. Install css-loader
  3. Create css file with add-on module at the file name ex: styles.css => styles.module.css

4.Import styles to component:

import styles from './styles.modules.css'

5.Add classname to JSX tag

    <div className={styles.header}> Hello world</div>
  1. Start styling your component by using normal CSS

Upvotes: 2

Bhojendra Rauniyar
Bhojendra Rauniyar

Reputation: 85593

You can use css specific to that component only:

page1.js

import './page1.css'
// page1 component

I suppose page1 component folder structure like:

page1/
  page1.css
  page1.js

Upvotes: 1

Related Questions