Table of contents
"RollTheDice5" is a simple application that displays an image of a dice and allows the user to roll the dice by pressing a button. It uses haptic feedback to improve the user experience and handles different dice images using custom types.
The code starts by importing the necessary dependencies from React and React Native, as well as some additional dependencies like
react-native-haptic-feedback
.Next, the dice images (DiceOne, DiceTwo, ..., DiceSix) are imported from the
assets
folder.A custom type called
DiceProps
is defined, which specifies that the props of aDice
component should include animageUrl
of typeImageSourcePropType
. This is used to ensure that theDice
component receives the correct image to display.An options object is defined, which will be used for haptic feedback on supported devices.
Next, the
Dice
component is defined, which takes theimageUrl
as a prop and displays the corresponding image.The
App
function is defined, which is the main component of the application. It uses theuseState
hook to maintain a current dice image state. The initial value is the image ofDiceOne
.The
rollDiceOnTap
function is used to change the dice image randomly when the button is tapped. It generates a random number between 1 and 6 and updates the dice image based on the generated number.ReactNativeHapticFeedback
is also used to provide haptic feedback to the user.Finally, the
App
component returns the structure of the application's user interface, which consists of a main container, theDice
component, and a button that calls therollDiceOnTap
function when pressed.
The index.d.ts
file is a TypeScript type declaration file that is used to declare the type of image files in the application. In this case, it declares the type of image files with the .png
extension. This allows TypeScript to recognize and verify the correct type of the imported images in the code.
Recommendations
I always followed the instructions in the documentation but sometimes things don't work so I did the following
in this case:
react-native-haptic-feedback npm
In my case I did not do what is in the image, I just installed the package and imported it into App.tsx.
my steps were:
Install the package npm i react-native-haptic-feedback
Import into App.tsx file import ReactNativeHapticFeedback from "react-native-haptic-feedback";
Use it inside the App.tsx file // Optional configuration const options = { enableVibrateFallback: true, ignoreAndroidSystemSettings: false, };
// Trigger haptic feedback ReactNativeHapticFeedback.trigger("impactLight", options);
Configurations in Smartphone Android:
Enable vibration
Enable haptic feedback
Disable battery saver
my code in github: