- Handling Android Back Button Events in React Native with Custom Components
- React Native and Android’s Back Button
- React Side Effect
- Implementing our Desired Android Behavior
- In conclusion
- Handling Android Back Button Press in React Native
- Android Back Button
- Event Listener for Back Button Press
- Add hardwareBackPress Event Listener
- Remove hardwareBackPress Event Listener
- Handle the event
- What we are going to do?
- To Make a React Native App
- Installation of Dependencies
- CocoaPods Installation
- Project File Structure
- Code to Handle Android Back Button
- App.js
- FirstPage.js
- SecondPage.js
- ThirdPage.js
- To Run the React Native App
- Output Screenshots
- Android react on button
- React Button CodeSandbox
- Default html button
- Button onClick
- Button text
- Default browser button styles
- Button Component Style
- Our restyled button with styled-components
- Button disabled
- Button as a link and redirect
- Button group
- Button toggle
- Material UI Buttons
Handling Android Back Button Events in React Native with Custom Components
As you build a React Native app across multiple platforms, one of the key differences between your iPhone and Android apps is that Android phones have a separate system back button that users can touch at any time.
As an Android user moves through your app and goes deeper and deeper into new scenes, the expected behavior is that a press on the back button returns the user to the previous screen, unless they are on the first screen, where a press on the back button means they exit the app.
The system Back button is used to navigate, in reverse chronological order, through the history of screens the user has recently worked with. It is generally based on the temporal relationships between screens, rather than the app’s hierarchy.
React Native and Android’s Back Button
The default React Native behavior for the back button is that pressing the button will exit the app.
React Native provides a BackAndroid module that gives developers control of back button behavior. This module is in charge of registering callbacks to decide what to do when the back button is pressed. When a user taps on the back button, the app runs through every registered event listener and only stops if one callback returns true . If no callbacks return true , the button press quits your app.
To implement the Back Button’s reverse chronological screen navigation as discussed by the Android Developer Guide, for example, a developer could write a callback that checks the current number of routes before deciding whether or not to exit the app:
This works well enough if this function is the only registered callback. But what happens when you need to add more and more event listeners to cover the business logic for different use cases? After all, the same Android developer guide writes that the back button can be used to dismiss dialogs and popups or to dismiss contextual action bars.
Imagine a screen that performs an expensive calculation, or multiple network calls, or a payment page where the user has submitted credit card information and you are waiting for a reply from the server. If someone presses the back button here, you may want to handle this press differently.
React Native’s out of the box experience means that each of these situations requires adding a new event listener when it is necessary and manually removing it when it is not. It becomes mentally taxing to keep a list in your head of which listeners are mounted and whether the functions return true values or false values.
On top of that, forgetting to remove a listener could lead to strange bugs! Without enough defensive coding, you could end up running your back-button-press on credit-card-submission function even if that view is no longer visible.
An easier way to think about this problem and avoid these bugs is by reframing the problem: instead of adding new listeners when your business logic changes, only ever mount one listener, and change that function when your business logic changes.
React Side Effect
Handling back button behavior is a perfect use case for Dan Abramov’s React Side Effect library. React Side Effect allows programmers to create special higher-order components that are designed to perform side effects when they are rendered and updated by your app.
One popular package that is implemented with React Side Effect is React Document Title, which allows programmers to change browser window’s title by passing a property to a component, like so:
React Side Effect fits with React’s component-based architecture because it allows wrapping of imperative APIs (like React Native’s BackAndroid or changing a document’s title) into components that better fit React’s programming model and abstractions.
The basic idea with React Side Effect is to create a React component that accepts any arbitrary props you define. This component is then wrapped with the withSideEffect function and two or three additional functions you implement. These functions are called, one after the other, every time your app re-renders and then emit a side effect based on the logic you provide. Here are their conventional names and behavior:
- reducePropsToState — The argument passed to this function is an array of the properties to all of the mounted instances of your component
- handleStateChangeOnClient — This function is called with the return value of reducePropsToState and is used to emit a side effect
- mapStateOnServer (optional) — This function behaves like handleStateChangeOnClient but is invoked on the server if your React app uses server rendering
A simple implementation of DocumentTitle may look like this:
Programmers can implement these functions in any manner they choose: some use cases could lend themselves to aggregating properties from many components together into one value. Other use cases, like this one, are only concerned with the value provided to the last component.
In either case, the return value of reducePropsToState is passed as the argument to handleStateChangeOnClient , where we use this argument to change the title of the document.
Implementing our Desired Android Behavior
Let us take a look at a more complicated example. Here are the basic rules: no matter how many AndroidBackButton components are rendered by our app at once, only the function provided as a property to the innermost rendered component should be executed. The return value of this function determines whether or not an Android button press quits the app.
This is implemented by ensuring that there is only ever one callback registered with React Native’s BackAndroid library. This callback will in turn call the function provided to the innermost AndroidBackButton instance. We will use React Side Effect to update the function that is called inside the event listener.
If you try this code as-is in your app, you may be surprised to find that it does not fully work. Namely, the reducePropsToState function executes while handleStateChangeOnClient does not. Why not?
The answer has to do with React Native’s execution environment and the way that React Side Effect determines how to invoke functions. Because React Side Effect can run on both the client and server, the library checks to see which environment it is in by asking if it has access to the DOM when it is time to emit a change.
React Native, as we know, does not render a DOM! Because React Native’s environment does not satisfy the conditions of this check, we cannot place our function as the second handleStateClientOnClient argument and must instead position it as the optional third argument, the rather confusingly (for us) named mapStateOnServer .
Despite the name of the function and the implication in a request-response world that this function is only called once, this function is called whenever a component is mounted, unmounted, or changed. We can rewrite the bottom of our above example as this:
With a working version of our component, we can now control back button behavior by rendering the component anywhere in our app’s view hierarchy. We can define even define a base behavior (for instance, navigating back unless the user is on the first screen of your app) and then override that behavior in certain contexts. All without manually juggling the addition and subtraction of event listeners!
In conclusion
I hope you learned something about React Side Effect and how higher order components can let you take advantage of React’s component abstraction to wrap imperative APIs and deal with changing data in your programs.
I’m open sourcing this component as “react-native-android-back-button.” View the source here, install it with npm install react-native-android-back-button , and let me know what you think!
Источник
Handling Android Back Button Press in React Native
Android Back Button
When the user presses the Android hardware back button in React Native, react-navigation will pop a screen or exit the app if there are no screens to pop. This is the sensible default behavior, but there are situations when you might want to implement custom handling. This is where handling the android back button is useful. You can also check react-navigation-backhandler library to handle the back press.
Event Listener for Back Button Press
To handle the Android Back Button Press in the React Native we have to register the hardwareBackPress event listener with a callback function, which will be called after pressing the Back Button. We should also remove the listener when we are jumping out from the screen (where we have added the listener) because sometimes after going to the next screen or any other screen the listener remains active in the background if the last screen is in the stack and not killed by the system.
T he event subscriptions are called in reverse order (i.e. last registered subscription first), and if one subscription returns true then subscriptions registered earlier will not be called.
Add hardwareBackPress Event Listener
Remove hardwareBackPress Event Listener
Handle the event
Returning true from onBackPress denotes that we have handled the event, and react-navigation’s listener will not get called, thus not popping the screen. Returning false will cause the event to bubble up and react-navigation’s listener will pop the screen.
What we are going to do?
In our example, we are going from FirstPage to SecondPage using navigate and after clicking Back Button on SecondPage we will navigate to ThirdPage with an alert. So let’s get started.
To Make a React Native App
Getting started with React Native will help you to know more about the way you can make a React Native project. We are going to use react-native init to make our React Native App. Assuming that you have node installed, you can use npm to install the react-native-cli command line utility. Open the terminal and go to the workspace and run
Run the following commands to create a new React Native project
If you want to start a new project with a specific React Native version, you can use the —version argument:
This will make a project structure with an index file named App.js in your project directory.
Installation of Dependencies
To install the dependencies open the terminal and jump into your project
Now run the following commands to install the dependencies
CocoaPods Installation
Please use the following command to install CocoaPods
Project File Structure
To start with this Example you need to create a directory named pages in your project and create three files FirstPge.js, SecondPage.js, and ThirdPage.js.
Code to Handle Android Back Button
Now Open App.js in any code editor and replace the code with the following code
App.js
Open pages/FirstPage.js in any code editor and replace the code with the following code.
FirstPage.js
Open pages/SecondPage.js in any code editor and replace the code with the following code.
SecondPage.js
Open pages/ThirdPage.js in any code editor and replace the code with the following code.
ThirdPage.js
To Run the React Native App
Open the terminal again and jump into your project using.
To run the project on an Android Virtual Device or on real debugging device
or on the iOS Simulator by running (macOS only)
Output Screenshots
That was the way to handle the Android Back Button. If you have any doubts or you want to share something about the topic you can comment below or contact us here. There will be more posts coming soon. Stay tuned!
Источник
Android react on button
In this guide we’re going to demonstrate various properties and types of Buttons you can render with React. For each example we will provide an example and the source code. All the examples can be found in the CodeSandbox below:
React Button CodeSandbox
Default html button
You can render a normal html with React, as usual React prop conventions apply, such as onClick , style , etc.
Button onClick
The button’s onClick prop is what allows us to add a function which fires when the user clicks on the button. In the above example, we define a function sayHello which alerts a message. Then, we use this function as the value of the onClick prop.
Button text
Changing the inner content between the button tags changes the text of the button. «Button Text» is between the two Button tags, and that sets the Button’s text.
This button looks very outdated, so we’ll show how to restyle this using styled-components.
Default browser button styles
Fun fact, if you inspect the default Button with the webkit inspector (right-click -> inspect), you can see the browser’s default styles defined in the user agent stylesheet.
Button Component Style
Using styled-components, we can create our own React button component and style it with css inside the template tag. If you’re not familiar with styled-components, check out our guide here. Styling a button is not much different than styling a div, except we’re adding styles on top of the browser’s already styled button, so the good news is that we don’t need to add too many properties here to make it look nice. For example, the html button’s text is already centered for us.
Our restyled button with styled-components
We mainly want to change the background color, increase the font size, add more padding (vertical then horizontal below), add a border radius, and change the cursor to a pointer. Doing those 5 things will give you a modern looking React Button you can use:
Button disabled
The html button already has a disabled property which disables the button, but we can to apply more styles to our Button when it’s disabled. Using the &:disabled selector, we’ll dim the button with a 70% opacity, change the text color and change the cursor back to the default.
Button as a link and redirect
Wrapping a button in a link tag transforms it into a link. Really any content you place in an tag will become a link, even images. Then, using the href property, you can redirect to a new page.
Button group
You can use flexbox to create a group of buttons.
Button toggle
In order to add toggle functionality we need to keep track of the state of which button is toggled. We’re going to use react hooks for that. We loop through a types array which we use for the text for the Button, but also as the string to keep track of which button is active. We initialize the useState hook with the first type from the array. Then, we loop over the types and render a ButtonToggle , which is extended from our other Button we had previously created so we could add styles to dim the opacity when it is not active (default). When it is active, it’s back to the normal opacity.
We check active , which is the current state, against the type that we loop over. When we click on the Button, we run our arrow function which calls the setActive setter. This sets the next active button to be whatever type we click on. This example is practically identical to our tabs guide except we remove the background on the Buttons to make them look like tabs there.
Material UI Buttons
If you’d prefer to use an open-source Button, check out our tutorial on Material-UI Buttons.
Источник