Skip to content

Library that enables users to consume Gamepad API inside React 🎮➡️⚛️

License

Notifications You must be signed in to change notification settings

nogiszd/react-ts-gamepads

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

23 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

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

🛫 Getting started

npm i react-ts-gamepads

There are two approaches: hook and context

useGamepads hook

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 and react-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 in useState to avoid type infering.

<GamepadsProvider> context

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.
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;
  1. 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.

📚 Credits

About

Library that enables users to consume Gamepad API inside React 🎮➡️⚛️

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published