简体   繁体   中英

Add and Remove css file on button click react js

I have an application in which I have two different css files for two totally different pages.

one.Component.js should include style1.css and two.Component.js should include style2.css

I have imported the css file separately in the component files. But when the components are loaded both the css gets conflicted and the page is collapsed.

one.Component.js:

import React, { Component } from "react";
import 'style1.css';

export default class ComponentOne extends Component {
    render() {
        return (
           <div class="theme-color">Hi</div>
        )
    }
}

two.Component.js:

import React, { Component } from "react";
import 'style2.css';

export default class ComponentTwo extends Component {
    render() {
        return (
           <div class="theme-color">Hi</div>
        )
    }
}

When this react application loads, both the css are loaded and hence there is a conflict.

Could any one help me out in getting the css file to load only when a particular page is rendered and not when the page is loaded.

Or it is possible to include one css files on button click and remove the other css files based on the component displayed.

Thanks in advance.

import styles from "./style.css"

This will add random string to your classes, hence it becomes component scoped

Use styles example:

<button className={styles.button}>Button</button>

Code for your exact case

Component 1:

import React, { Component } from "react";
import style from 'style1.css';

export default class ComponentOne extends Component {
    render() {
        return (
           <div className={style.theme-color}>Hi</div>
        )
    }
}

Component 2:

import React, { Component } from "react";
import style from 'style2.css';

export default class ComponentOne extends Component {
    render() {
        return (
           <div className={style.theme-color}>Hi</div>
        )
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM