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?
CodePudding user response:
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 />
};
}