#react-native React Native | Haptic Feedback and Images

#react-native React Native | Haptic Feedback and Images

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 a Dice component should include an imageUrl of type ImageSourcePropType. This is used to ensure that the Dice 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 the imageUrl as a prop and displays the corresponding image.

  • The App function is defined, which is the main component of the application. It uses the useState hook to maintain a current dice image state. The initial value is the image of DiceOne.

  • 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, the Dice component, and a button that calls the rollDiceOnTap 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:

  1. Install the package npm i react-native-haptic-feedback

  2. Import into App.tsx file import ReactNativeHapticFeedback from "react-native-haptic-feedback";

  3. 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:

  1. Enable vibration

  1. Enable haptic feedback

  1. Disable battery saver

my code in github:

RollTheDice5 Haptic Feedback and Images