0

I use styled components and have a mixin with many default parameters similar to this

`export const myMixins = {
   font: (
       fontFamily = 'Arial',
       weight = 600,
       size = '10px',
       style = 'normal') => `
       font-family: ${ fontFamily };
       font-size: ${ size };
       font-style: ${ style };
       font-weight: ${ weight };
   `
};` 

I used the default params to avoid passing all of them when it is not needed. But when I try to run this, it only works if I pass all of them, like this: ${ myMixins.font('Roboto', 'bold', '9px', 'normal') }; I also tried assigning null to params, but nothing changed. When I try to run it my IDE stills displays placeholders for all parameters and it won't work otherwise. I also tried to use keywords like $size but could not figure out the proper syntax nor did I find it anywhere on the web. I would like to be able to pass only the specific parameter that I want to change. Any help is much appreciated.

Kiki
  • 117
  • 1
  • 3

1 Answers1

1

I believe something like this would resolve your issue:

export const myMixins = {
  font: (
    fontFamily?: string,
    weight?: number,
    size?: string,
    style?: string
  ) => `
       font-family: ${fontFamily || 'Arial'};
       font-size: ${size || 600};
       font-style: ${style || '10px'};
       font-weight: ${weight || 'normal'};
   `,
}
Despina Kastani
  • 832
  • 5
  • 11
  • thank you for your answer. Ideally I would like to be able to call the mixin like this ${ myMixins.font($size:'9px') } BUT with your implementation I managed to call like this myMixins.font(null,'9px' } which is much better than placing all arguments. – Kiki Feb 09 '21 at 21:19
  • 1
    In JavaScript, you cannot pass parameters by reference, so you have to pass the unprovided variables with `undefiend` or `null` as you did. – Despina Kastani Feb 11 '21 at 13:29
  • 1
    Also a pitfall of that implementation is that since weight accepts number passing it `0` it will falsely result to the default presets - I know highly unlikely but still a possible number - – Despina Kastani Feb 11 '21 at 13:31