Library that enables users to consume Gamepad API inside React
npm install react-ts-gamepads> Library to support Gamepad API in modern React ⚛️
This is a maintained fork of react-gamepads with detailed TypeScript types and updated libraries.
!React !Typescript !License !npm
``bash`
npm i react-ts-gamepads
There are two approaches: hook and context
With this hook you can retrieve all gamepad inputs. This allows you to have a component "react" to gameplay input as it's received.
In this example, we take the input and set the component's state to it. This lets you use the state inside the component and have it change.
`jsx
import { useState } from 'react';
import { useGamepads, GamepadRef } from 'react-ts-gamepads';
const App = () => {
const [gamepads, setGamepads] = useState
useGamepads(gamepads => setGamepads(gamepads));
return
export default App;
`
> Difference between react-gamepads and react-ts-gamepads are that this library is strongly typed, although original library is also written in TypeScript.useState
> You can import provided types and use them in to avoid type infering.
With context, you can have parts (or the entire app) to subscribe to the state changes, in that case _gamepad state_.
1. Make an consumer component with the usage of useContext hook.
`jsx
import { useContext } from 'react';
import { GamepadsContext } from 'react-ts-gamepads';
const Example = () => {
const { gamepads } = useContext(GamepadsContext);
return
export default Example;
`
2. Wrap your App.tsx (or another main file) in the Provider and import your newly made component
`jsx
import { GamepadsProvider } from 'react-ts-gamepads';
import Example from './components/Example';
const App = () => {
return (
);
};
``
It is your choice which approach you will choose, or which fits your usage better.