Using Swiper in WebSharper
Below I’ll go through the very basics of Swiper and the differences when reaching for its abilities from WebSharper. You can assume that everything else works just as it is described in Swiper’s API documentation.
The next step is to get an instance of the Swiper class. There are two ways to do this: You can either pass the HTML class selector of your Swiper container (
.swiper-container in this case) or you can pass the selector and a configuration object. Here, the syntax to create the configuration object is just a little different in F#.
As I said, the API is mostly the same as the original (see the documentation here). There are some minor differences though, which I’ll list right below.
Method and property names
By F# naming conventions, all class-level names (e.g. methods, properties) start with a capital letter, so look out for that.
To pass DOM elements (
WebSharper.Javasctript.Dom.Element) to functions, you can call the
Dom property of an
Elt, or you can also call the
Html property of any
Elt to get the HTML string representing that
When a field of the config object can have multiple types, it appears as a
Some parameters in the config object can be assigned either a
string or a
Dom.Element, which means they'll have the type
Union<Dom.Element, string>. To instantiate such a type with a
string value, use
Union2Of2 "example". To create it with a
Union1Of2 elt.Dom. The pattern is the same for different types and sizes of unions.
When using the
Union<> type in C# you can simply assign a value of any of the appropriate generic type parameters since there’s an implicit conversion for every case.
string constants. For example, instead of just passing
'horizontal' to the
direction field, you have to use the following syntax:
To see the full list of affected types and fields, refer to the WebSharper.Swiper documentation.
WebSharper is all about easy reactive web development, so let’s look at what we can do with Swiper.
Let’s say you want your client to behave differently depending on the active slide in Swiper. To achieve this, first you’ll have to create a reactive variable with
let currentSlideIndex = Var.Create 0, where 0 stands for the default active index. (If you want to make sure that your first slide is indeed the one with the 0 index, add
InitialSlide = 0 to your config object.)
Now we have to update this reactive variable whenever we change slides. One way to do this is to add a fitting callback function in our config. The
OnSlideChangeStart parameter seems good for this purpose.
Great! All we have to do now is make our page react to the changes of the variable using
Note: for the snippet to work, make sure that you have the Swiper element hierarchy and an element with the id
mainin your HTML template.
To see a little more sophisticated version of this idea, please look at this presentation example, which won’t let you past a question slide until you click the correct answer.
Get Swiper for WebSharper