0

How change the @import according to value button in React?

Example of how i want: i have the this.state.modal = false

.js:

handleChange = () => {
  this.setState({
    modal: !this.state.modal
  })
}
<button onClick={this.handleChange}>Test</button>

and my .scss:

if(this.state.modal === true) {
  @import 'theme/white';
} else {
  @import 'theme/black';
}

of course i can't call if with .scss but basically is this what i want

3 Answers3

0

You can try something as described in this StackOverflow post.

https://stackoverflow.com/a/46543835/2853568

It returns a promise and the result of the promise resolution is the module you would conditionally wish to import.

VigSank
  • 62
  • 8
0

There are multiple ways of doing styles.

You can add/change class based on your state and handle css based on parent class.

<div className={this.state.modal ? "BlackTheme" : "WhiteTheme" }>
   {rest of your content}
</div>

In your scss

.BlackTheme {
   .button {
       background:black;
   }
}


.WhiteTheme {
   .button {
       background:white;
   }
}
Amit Chauhan
  • 6,151
  • 2
  • 24
  • 37
0

There are conditional rendering for SASS where you could for instance use a mixin mentioned here https://stackoverflow.com/a/13879344/7296909 or here https://github.com/sass/sass/issues/451#issuecomment-359489037

However, you can't set any variables in SASS with JS. You could however, as mentioned by @eramit2010, set different classes depending on the value e.g.:

const color = this.state.modal === true ? 'white' : 'black';
const className = ´theme ${color}´;

and then in scss:

%loadFileWhite {
  @import "theme/white";
}

%loadFileBlack {
  @import "theme/black";
}

.theme .white{
    @extend %loadFileWhite;
}

.theme .black{
    @extend %loadFileBlack;
}
Jesper
  • 2,044
  • 3
  • 21
  • 50