I am using scalajs 0.6.15 with scalajs-react 0.11.3 and reactjs 15.4.2.
Consider a component SomeComp
where the type of a value of the Props
needs to be parameterized.
Since the type needs to be known when using the component builder I wrap the component inside a class.
class SomeComp[T]() {
case class Props(t: T, onChange: T => Callback)
val component = ReactComponentB[Props]("SomeComp")...
def apply(t: T, onChange:T => Callback) = component(Props(t, onChange))
}
this works. the problem is, that the component gets remounted with every rerender of the parent, unless the user of SomeComp
creates first an instance of SomeComp
and uses this instance in the parent's render
method.
my hack solution to avoid this is:
object SomeComp {
val genericComp = SomeComp[Any]()
def apply[T](t: T, onChange: T => Callback) = genericComp(
t = t,
onChange = (a: Any) => onChange(a.asInstanceOf[T])
)
}
is there a better, less boilercode, less awful way? any suggestions?
Update After @Golly's (thx for your elaborate answer!) suggestions I find the second solution most elegant and want to post it here for completeness:
object SomeComp {
trait Props{
type T
val t: T
val onChange: T => Callback
}
// use Props#T if you need to reference T
val component = ReactComponentB[Props]("SomeComp")...
def apply[_T](_t: _T, _onChange: _T => Callback) = {
val props = new Props {
type T = _T
val t = _t
val onChange = _onChange
}
component(props)
}
}