0

I want to

  1. import a style class from a CSS file
  2. dynamically extend or override the style
  3. Apply the new style to react component.

Pseudocode of what I want to achieve

import 'common.css'

function MyComponent() {

    if (somethingHappened) {
        style = extendOverrideStyle(styleClassFromCSS)
    } else {
        style = styleClassFromCSS
    }

    return (
        <SomeComponent className=style />
    )
}

How can I do this?

Update: Check my answer in the replies for how I finally did this.

1
  • Why don't you add a class and based on it change the styling? Commented Dec 19, 2019 at 10:39

3 Answers 3

2

Just create a new class in your CSS file to override the old CSS. Then do it as

function MyComponent() {
    return (
        <div className={somethingHappened ? 'firstclass overwriteclass' : 
       'firstclass'}>
        <SomeComponent />
      </div>
    )
}
Sign up to request clarification or add additional context in comments.

Comments

0

You can't set style in Component Directly. First you need to pass the style as prop to your Component and set style inside that component

<SomeComponent prop_class={your_style}/> 

Inside SomeComponent

<div className={this.props.your_style}>

</div>

Comments

0

Answer (implementation somewhat similar to @Rohan's answer):

The main css class is the base style rules and .main.somethingHappened extends/overrides it. The main css class is applied to myComponent initially. When somethingHappened is true, apply both css classes main somethingHappened to myComponent.

mystyle.css

.main {
   ...
   margin: 10px;
}

.main.somethingHappened {
   margin: 5px
   padding: 5px;
}

myComponent.js
(uses classnames library. check @Rohan's approach to avoid classnames library.)

import 'common.css'
import classnames from 'classnames'

function MyComponent() {

    let didItHappen = ...

    return (
        <SomeComponent 
           className={classnames('main', {'somethingHappened': didItHappen})} 
        />
    )
}

Comments

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.