0

I have 2 different pages and a .css file for each page. Both have a class selector with the same name, but only one of them is applied. I've only worked with react-native so far, and had both the content and the styling in the same file. I couldn't figure out what is happening...

Let's say we have the following css class:

.container {
  display: flex;
  align-items: center;
  justify-content: center;
}

Even if the css file is not imported in one file, the class is applied to a div, if it's given in className.

For example, we have 2 files: CarPage.tsx and BikePage.tsx. The container class is imported in CarPage, but it's used in BikePage and it is applied. Does anyone know if this is how it should work?

1 Answer 1

1

In React, once CSS is imported, it will be "combined" and applied to the entire DOM. React uses CSS files as global scope.
In order to achieve locally scoped CSS, you will have to use:

CSS module

Create `[name].module.css` file then:
import React, { Component } from 'react';
import styles from './example.module.css';

class Example extends Component {
    render() {
        return <button className={styles.container }>Button</button>;
    }
 }
 export default Example;

using libraries such as styled-components).

  class Example extends Component {
         const Button = styled.button`
           background: transparent;
           border-radius: 3px;
           color: red;
           margin: 0 1em;
           padding: 0.25em 1em;
           `
          render(){
           return  <Button /> 
           };

 }
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for helping me! Tried it with CSS module.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.