Search code examples
reactjsoffice-ui-fabricoffice-fabric

Office UI Fabric - How to apply css styles to existing components


I'm using the provided components and every time I need to change a component style I wonder what's the proper way to do it.

Lets say I need to change the IconButton background color when it's disabled. https://codepen.io/elsl/pen/KrQQdV

If I provide a theme, how am I supposed to know which palette/semanticColor is used by that component?

const iconsTheme = Fabric.createTheme({
  semanticColors: {
    disabledBackground: "#ff9933"
  }
});
    

<Fabric.IconButton
  iconProps={{iconName:'ChevronRight'}}
  disabled
  theme={iconsTheme}
/> 

If I provide an IButtonStyles, how am I supposed to know that the property name is "rootDisabled.backgroundColor"?

const iconButtonStyles: IButtonStyles = {
       rootDisabled: {
         backgroundColor: "#ff0000",
       }
};

<Fabric.IconButton
   iconProps={{iconName:'CalculatorEqualTo'}}
   disabled   
   styles={iconButtonStyles}
/>

For both these options, I had to dig into the component's source code on github to find out.

Is this the expected/correct way? If so, between creating a Theme or an IStyle which would be the ideal/best practice?


Solution

  • Theme vs IStyles

    I would say, use a Theme if you want all Fabric components to have the same customization.

    Use the styles property if you just want to customize that specific component (or that one specific instance of the component).

    How to discover the styling hooks if using IStyles

    There are four ways that comes to mind.

    1. Look at the documentation (e.g. https://developer.microsoft.com/en-us/fabric#/components/dropdown, look at the IDropdownStyles interface) (screenshot)
    2. Utilize IntelliSense if you're using an editor like Visual Studio Code, which automatically enumerates the IComponentStyles and provides documentation if any.
    3. Inspecting the DOM often provides hints (the hook areas usually look like {area}-{number} so root-33 for instance where the "area" name is root.
    4. Read the source code.

    Unfortunately for option 1 and option 2, Fabric React isn't super consistent with the IComponentStyles documentation so not all components have equally descriptive comments and in those cases, you may need to fallback to option 3 and option 4.