Use a Cycle.js Component in the main() Function

André Staltz
InstructorAndré Staltz

Share this video with your friends

Send Tweet
Published 6 years ago
Updated 3 years ago

We have made a Cycle.js app for generic labeled slider which can be configured through props, but how can we reuse it in other Cycle.js apps? This lesson shows how we can embed any Cycle program inside a larger Cycle program in a very simple manner.

[00:00] Now, we have a generic labeled slider that can be configured through these props, but how could I reuse this labeled slider in other Cycle.js apps? First of all, notice that main is not a special name. There is nothing really magical about it. It's just a function which is passed here to Cycle run.

[00:20] I could rename this to labeled slider, if I want. Then I used labeled slider in Cycle run, and this is exactly the same app. Besides that, I could write another function which is called main this time, and takes sources, and returns sinks, where those sinks are coming from the function call of labeled slider. We're passing sources.

[00:48] It's really just wrapping the labeled slider. If I use main now in Cycle run, this is going to work just like before. Wait a minute. Main is where we write the application logic, and there you go. This is how labeled slider is now a component, and we're using it from within main.

[01:09] We just achieved reusable components, and that wasn't that hard after all. We literally have a Cycle.js app inside another Cycle.js app. That's because Cycle.js apps are simply functions that take sources and return sinks.

[01:24] The main now is taking sources.dom and sources.props, passing that to labeled slider, and then also forwarding the sinks that it got from the labeled slider. I could actually in fact move the props from the driver into the main, because this is just a stream.

[01:42] I can create the stream called props stream, which is a stream of just one those object. Then I could pass as the sources to the sliders, I'm going to object spread the sources to the main. Basically, labeled slider is going to have all of the sliders that the main has, except here for props, we're going to use props stream.

[02:05] Then I can actually just eliminate this fake driver, because the only purpose of that was to create this prop stream to pass to the labeled slider. We already are able to achieve that here in the main. This still works, just like before.

[02:25] Now, we only have real drivers, not any fake drivers. Real drivers do effects with external world. Now, we can customize our component from within main. Then we can continue building logic around the component, and logic should go in main.