Writing React components in Slinky is just like writing them with the native ES6 API.
Slinky components must define the type of their React props and implement a render method. Within the component, you can access the props using the
To use a component, call the generated companion object's apply method with the parameters defined in props.
To pass in keys and refs, use
To make your component stateful, extend the
Component class (instead of
StatelessComponent) and define your state type and initial state
Then you can access the state with
state and use
setState to update your component's state. Slinky supports all variants of
setState, such as the one that takes the previous state as a function parameter.
So a full component would look something like this:
Props and State Type Definitions
When defining the
State types, Slinky accepts any type definition, so you can define these types as type aliases, case classes, or even regular classes. For example, if we had a component that takes a single
String as its props, we could define it as:
props is the
String value passed in from a parent.
With Slinky 0.2.0, the
@react macro annotation was introduced to reduce the boilerplate involved with creating components. Most examples in the documentation will use the macro annotation, but it is always possible to use the no-annotation API with just a few changes.
If you have a component that looks like this:
The macro annotation converts this code into something like this:
And in the case of a
StatelessComponent something like this:
Slinky supports all of the React component lifecycle methods, including the next-generation ones from React 16.
Static Lifecycle Methods
To use lifecycle methods defined in a static context, override the lifecycle method inside the companion object if using
@react style or directly inside
ComponentWrapper if using the non-annotation style.
Or with the
To use the new snapshot based lifecycle from React 16.3, define the
Snapshot type and implement
getSnapshotBeforeUpdate and the variant of
Or with the