I'm working on a react app where I need to make use of bootstrap for one of the components. But bootstrap is getting applied to every component and all the previously styled components are getting disturbed. This makes sense as CSS is globally applied in React. Is there a way to achieve this?
(Note:
I know there is one trick where we can wrap all the imports of the "bootstrap.scss" file into a local class and re-compile the bootstrap file. But after wrapping, when I hit npm install
in the root directory of bootstrap, it threw so many errors and depreciation warnings. In case if this trick is working for you, I would appreciate if you drop me the compiled source code.)
In order to apply Bootstrap styles to only a specific component in React, you might consider using CSS Modules. This feature essentially lets you utilize class names in a localized manner within your component, thereby preventing style leakage to other components.
The process would involve importing Bootstrap styles within a CSS module and then exclusively utilizing them within the desired component. Here's a simple demonstration of how you could implement this:
// MySpecificComponent.module.css
@import "~bootstrap/dist/css/bootstrap.min.css";
// MySpecificComponent.js
import React from 'react';
import styles from './MySpecificComponent.module.css';
function MySpecificComponent() {
return (
<div className={styles['container']}>
<button className={styles['btn']}>A Button</button>
</div>
);
}
export default MySpecificComponent;