0

I am working on a project where there is a main style.scss file for a number of components. I want to restructure the code so as every component has its own folder (index.js, styles.scss). There is a nested class that is using a class from another component and now that I have to separate all the styles, this part is broken. I can't use composition since it is a nested class. What other approaches can I take?

The code looks like this:

// Component A styless.scss

.component-a-class {

}

// Component B styless.scss 

.component-b-class{

.component-a-class {

  }
}
Adam
  • 3,829
  • 1
  • 21
  • 31
slwjc
  • 27
  • 7

1 Answers1

0

Use Sass's @import directive to import the external classes. Your code would become something like this:

// ComponentA/styless.scss

.component-a-class {
  ...
}

// ComponentB/styless.scss 

.component-b-class{
    @import "../ComponentA/styless.scss"
}

This will inject .component-a-class into the .component-b-class as a nested rule.


Edit: To import a style and also be able to modify one of its properties' values, you have to make use of Sass mixins:

// ComponentA/styless.scss

@mixin component-a-class($width: 100) {
    .component-a-class {
        width: $width + px;
    }
}

@include component-a-class();

// ComponentB/styless.scss

@import "../ComponentA/style.scss";

.component-b-class{
    @include component-a-class(500);
}

This will get you what you want, though it isn't ideal. The resulting compiled ComponentB/styless.css file will include everything written in ComponentA/styless.scss because the @import directive is an "all-or-nothing" feature (there is no selective import). The result would look like this:

// ComponentB/styless.css (compiled)

.component-a-class {
  width: 100px;
}

.component-b-class .component-a-class {
  width: 500px;
}
Adam
  • 3,829
  • 1
  • 21
  • 31
  • 1
    This doesn't seem to be working. I forgot to mention that I also want to change the width of the whole component-a-class from component-b-class – slwjc Sep 09 '18 at 16:49
  • Updated to include further clarification. – Adam Sep 09 '18 at 21:01