avaneeshtripathi / react-dice-roll

A highly customizable dice roll package built in react.
https://www.npmjs.com/package/react-dice-roll
34 stars 23 forks source link

How can i use trigger #13

Closed nguyentung19 closed 1 year ago

nguyentung19 commented 2 years ago

How can i use triggers? please help me

avaneeshtripathi commented 2 years ago

@nguyentung19 For triggers, You can pass an array of keycodes and when you press any of those keycodes, dice will roll.

here is the reference: https://github.com/avaneeshtripathi/react-dice-roll#usage-1

thereturn932 commented 1 year ago

Is it possible to trigger it with another function?

vlpreddy commented 1 year ago

Is it possible to trigger it with another function?

looking for same.

shahab65 commented 1 year ago

I had the same problem and was able to solve it using the following approach:
First, import React and Dice from "react" and "react-dice-roll", respectively. Then, define two custom types for use with the Dice component: DiceNumbers, which represents the possible values of the dice (1 through 6), and TDiceRef, which defines the shape of the ref object that will be used to interact with the Dice component.

import React, { useRef } from "react";
import Dice from "react-dice-roll";
type DiceNumbers = 1 | 2 | 3 | 4 | 5 | 6;
type TDiceRef = {
  rollDice: (value: DiceNumbers) => void;
};

Next, create a useRef hook and assign its return value to a constant called diceRef. This ref object will be used to store a reference to the Dice component. Additionally, define a function called onRoll that will be called when the "Roll" button is clicked. This function simply calls the rollDice method on the current property of the diceRef object, passing in a value of 3.

  const diceRef = React.useRef<TDiceRef>(null);
  const onRoll = () => {
    diceRef.current?.rollDice(3);
  };

Finally, add a button to your JSX that will trigger the onRoll function when clicked. Also, add the Dice component to your JSX and pass the diceRef object to it via the ref prop.

<div>
  <button onClick={onRoll}>Roll</button>
  <Dice ref={diceRef} />
</div>

Overall, this approach allows you to interact with the Dice component imperatively, using a custom ref object and type definitions that you define yourself. This can be helpful when dealing with third-party libraries that may not provide the types or props that you need.