Dynamic components

Dynamic components mean components that generate styles based on their props. You can derive styles from props, apply conditionally a variant or any logic.

styled.{{tag}} allows to be defined by a function, where it should return a string. This function is going to be available as props API for that component, including all props from the element. Like following:

module Dynamic = %styled.div(
  (~color, ~background) => `
    color: $(color);
    background-color: $(background);
  `
)
 
<Dynamic color=CssJs.hex("#EB5757") background=CssJs.hex("#516CF0")>
  {React.string("Hello!")}
</Dynamic>
module Dynamic = %styled.div(
  (~color, ~background) => `
    color: $(color);
    background-color: $(background);
  `
)
 
<Dynamic color=CssJs.hex("#EB5757") background=CssJs.hex("#516CF0")>
  {React.string("Hello!")}
</Dynamic>

Note: The returned expression (the last expression of the function) need to be an string (it can't be a reference or a function call). This is a limitation of ppxes where it needs to check the current AST to know which type is.

All rules from Interpolation are applied here. In the example, color and background are CssJs.Color.tCssJs.Color.t since it gets inferred from the CSS property. It's called type holes https://twitter.com/davesnx/status/1552305210558742528

Collision

If you create a dynamic component with a prop that collides with the name of a React prop, it will override it. For example if your dynamic component is defined with a prop "size" it will override size from makeProps. This mechanism is to ensure that you can name your props the way you want it.