Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Provide implicits for using React inline-style #97

Open
jonas opened this issue Oct 11, 2016 · 0 comments
Open

Provide implicits for using React inline-style #97

jonas opened this issue Oct 11, 2016 · 0 comments

Comments

@jonas
Copy link

jonas commented Oct 11, 2016

Material-UI makes heavy use of React inline-styles for styling the components, which unfortunately doesn't seem to make it easy to use this library. At least I didn't find a way to convert ScalaCSS style objects to a js.Object which adheres to the property naming convention for React inline-styles and can be passed to Material-UI.

Specifically, I am using the Material-UI Scala.js bindings where inline styles can be provided as js.Any, and right now I pass them using: scala.scalajs.js.Dynamic.literal("padding" -> 4). It would helpful to also allow ScalaCSS styles to be used in such places via an implicit.

The following example code achieves this although not in a particular clean way (instead of StyleA it might be better to simply use AVs or extend another StyleSheet trait), but before submitting a PR I wonder if you are interested in supporting the above use case and if yes, what is your suggested approach.

final def styleA2JsAny(css: StyleA): js.Any = {
  val result = js.Dictionary.empty[String]
  css.style.data.values.flatMap(_.avStream).foreach { property =>
    // Map CSS property name to react style naming convention.
    // For example: padding-top => paddingTop
    val propertyName = property.attr.id.split("-") match {
      case Array(head, other @ _*) => head + other.map(_.capitalize).mkString
    }
    result(propertyName) = property.value
  }
  result
}

/** Convert a ScalaCSS style to a an object as required by the Material-UI Scala.js bindings. */
implicit final def styleA2UndefOrJsAny(s: StyleA): js.UndefOr[js.Any] = styleA2JsAny(s)

/**
 * Implicit to convert ScalaCSS styles to Scala.js React `style` attribute
 * values:
 * {{{
 * val noPadding = style(padding(0.px))
 * <.div(^.style := noPadding)(...)
 * }}}
 */
implicit val styleA2ValueType: ValueType[StyleA] =
  ValueType.map(styleA2JsAny _)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant