Library to support Gamepad API in modern React ⚛️
This is a maintained fork of react-gamepads with detailed TypeScript types and updated libraries.
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.
import { useState } from 'react';
import { useGamepads, GamepadRef } from 'react-ts-gamepads';
const App = () => {
const [gamepads, setGamepads] = useState<GamepadRef>({});
useGamepads(gamepads => setGamepads(gamepads));
return <div>{gamepads[0].buttons[4].pressed}</div>;
};
export default App;
Difference between
react-gamepads
andreact-ts-gamepads
are that this library is strongly typed, although original library is also written in TypeScript. You can import provided types and use them inuseState
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.
- Make an consumer component with the usage of
useContext
hook.
import { useContext } from 'react';
import { GamepadsContext } from 'react-ts-gamepads';
const Example = () => {
const { gamepads } = useContext(GamepadsContext);
return <div>{gamepads[0].buttons[4].pressed}</div>;
};
export default Example;
- Wrap your
App.tsx
(or another main file) in the Provider and import your newly made component
import { GamepadsProvider } from 'react-ts-gamepads';
import Example from './components/Example';
const App = () => {
return (
<GamepadsProvider>
<Example />
</GamepadsProvider>
);
};
It is your choice which approach you will choose, or which fits your usage better.