Component-scoped CSS is proper to avoid CSS class name clashes. React Js allows you to use CSS modules to work around this problem. You can use CSS modules in your React Js application if your
The issue we face using CSS is the class name conflicts. When you import the CSS file, the CSS classes defined in the CSS file become global. In other words, any CSS files imported into your component are visible throughout the application.
In the below example, I imported the Styles.css file in the
.buttonClass {
background-color: green;
color: white
}
.spanClass {
color: rgb(11, 222, 85);
}
.divClass {
margin: 24px;
}
import SuccessMessage from "./components/SuccessMessage"
import ErrorMessage from "./components/ErrorMessage"
import { useState } from "react"
export const App = () => {
const [message, setMessage] = useState("success")
const toggleMessages = () => {
setMessage((prev) => {
return prev === "success" ? "error" : "success"
})
}
return(
<>
{message === "success" && <SuccessMessage/>}
{message === "error" && <ErrorMessage/>}
<div className="divClass">
<button onClick={toggleMessages}>Show {message === "error" ? "Success" : "Error"} message</button>
</div>
</>
)
}
export default App
Importing
import "../Styles.css"
const SuccessMessage = () =>{
return(
<div className="divClass">
<span className="spanClass">Your Account has been created successfully</span>
<br/>
<button className="buttonClass">Go to account</button>
</div>
)
}
export default SuccessMessage
The
const ErrorMessage = () =>{
return(
<div className="divClass">
<span className="spanClass">We could not create your account</span>
<br/>
<button className="buttonClass">Contact customer service</button>
</div>
)
}
export default ErrorMessage
If your app uses
.buttonClass {
background-color: green;
color: white
}
.spanClass {
color: rgb(11, 222, 85);
}
.divClass {
margin: 24px;
}
import styles from "./SuccessMessage.module.css"
import "../Styles.css" //we have duplicate class names here
const SuccessMessage = () =>{
return(
<div className={styles.divClass}>
<span className={styles.spanClass}>Your Account has been created successfully</span>
<br/>
<button className={styles.buttonClass}>Go to account</button>
</div>
)
}
export default SuccessMessage
.buttonClass {
background-color: red;
color: white
}
.spanClass {
color: red;
}
.divClass {
margin: 24px;
}
import styles from "./ErrorMessage.module.css"
const ErrorMessage = () =>{
return(
<div className={styles.divClass}>
<span className={styles.spanClass}>We could not create your account</span>
<br/>
<button className={styles.buttonClass}>Contact customer service</button>
</div>
)
}
export default ErrorMessage
The usage of CSS classes is a little different. I use
CSS modules enable CSS classes to scope to the component level. It allows us to solve CSS class name clashes by generating dynamic and unique class names.