📺 "One project. One language. Three apps." Learn more in our upcoming code sharing webinar!

NativeScript Core

Button

The Button widget provides a standard button widget that reacts to a tap event.

const Button = require("tns-core-modules/ui/button").Button;
import { Button } from "tns-core-modules/ui/button";

Basics

The Button widget comes with text property and a tap handler. The example demonstrates how to set a button in XML page and use the tap callback.

<Button text="Tap Me!" tap="onTap" class="btn btn-primary btn-active" />
function onTap(args) {
    const button = args.object;
    button.text = `Tapped ${count} times`;
}
exports.onTap = onTap;
export function onTap(args: EventData) {
    const button = <Button>args.object;
    button.text = `Tapped ${count} times`;
}

Improve this document

Demo Source


Code Behind

Creating a Button programmatically with text value and a tap callback.

const myButton = new Button();
myButton.text = "Tap me!";
myButton.className = "btn btn-primary btn-active";
myButton.on("tap", (data) => {
    // args is of type EventData
    alert("Button Tapped!");
});
const myButton = new Button();
myButton.text = "Tap me!";
myButton.className = "btn btn-primary btn-active";
myButton.on(Button.tapEvent, (data: GestureEventData) => {
    // data is of type GestureEventData
    alert("Button Tapped!");
});

Improve this document

Demo Source


Styling

To style and customize the Button widget use the conventional CSS properties and Icon Fonts. The widget also supports the CSS pseudo-selector active which will be triggered when the button is pressed. The example below shows a button with icon (using icon font), several CSS properties and with an active state styling.

.my-button {
    background-color: orangered;
    border-radius: 5;
    color: white;
    font-family: FontAwesome;
    font-size: 24;
    vertical-align: middle;
    width: 80%;
}

.my-button:active {
    background-color: lightslategray;
    color:white;
}
<Button text="&#xff17b; Tap Me!" tap="onTap" class="my-button" />

Improve this document

Demo Source


API Reference for the Button Class

Native Component

Android iOS
android.widget.Button UIButton