Buttons & Alerts in React-Native
Implementing Buttons in React-Native
The button component in React-Native is like all other components and can be auto imported, by starting to type the <Button> you should see an auto import drop-down, just be careful when using this as it can sometimes auto import from the react-native web or other libraries. In these examples I am importing form "react-native". With buttons the self-closing syntax can be used because there is nothing added between them. Give the button a title (title="Tap Button") or your choice of words and handle the onPress event by passing a function. I'll use the console.log for these examples (onPress={() => console.log("Button Tapped")}>) Each platform displays the button according to its native components.
Button Code with console.log |
Console logging the message |
Alerts with React-Native
![]() |
Button Displayed on iPhone |
![]() |
Button Tapped message |
The alert messages can be changed to allow for more specific messaging. We can do this by importing the Alert API from react-native. This allows the use of methods like alert and prompt (to get an answer). The first example is the alert method, this method has a few parameters the first is the title of the alert box, the second is the alert massage and the third is the button that can be changed to an array of buttons used to get an answer. For example,
onPress={() => Alert.alert(“Title”, “Message”, [
{text: “Yes” onPress: () => console.log(“Yes”) }
, {text: “No” onPress: () => console.log(“No”) }
])}
/>
in this example I have added an array of two buttons and handled the onPress event by adding a console.log for each button giving a different answer.
Yes and No selections |
![]() |
Yes or No prompt on iPhone |
Now I will go over the prompt method. The prompt method also holds three parameters (A title, message and call-back function or buttons.) The call-back takes a parameter of type string, this is the text that the user enters into the box. I will console.log the user input text by passing a function of the third parameter
(Alert.prompt(“Title”, “Message”, (text)
=> console.log(text)).
![]() |
Prompt message |
![]() |
Text Input on prompt message |
Console logging text input |
In the next post I will go over locally stored and network images
Really interesting! Looking forward to the next one
ReplyDelete