score:0
Accepted answer
so here is one possible solution to solve this
function usekeypress(targetkey) {
// state for keeping track of whether key is pressed
const [keypressed, setkeypressed] = usestate(false);
// if pressed key is our target key then set to true
function downhandler(e) {
if (e.key === targetkey) {
setkeypressed(true);
e.preventdefault();
}
}
// if released key is our target key then set to false
const uphandler = (e) => {
if (e.key === targetkey) {
setkeypressed(false);
}
};
// add event listeners
useeffect(() => {
window.addeventlistener("keydown", downhandler);
window.addeventlistener("keyup", uphandler);
// remove event listeners on cleanup
return () => {
window.removeeventlistener("keydown", downhandler);
window.removeeventlistener("keyup", uphandler);
};
}, []); // empty array ensures that effect is only run on mount and unmount
return keypressed;
}
export function useui() {
const scrolldistance = 15;
const arrowup = usekeypress("arrowup");
const arrowdown = usekeypress("arrowdown");
const k = usekeypress("k"); // up
const j = usekeypress("j"); // down
const w = usekeypress("w"); // up
const s = usekeypress("s"); // down
useeffect(() => {
if (!(arrowup || arrowdown || k || j || w || s)) {
return null;
}
const scrolldirection = arrowup || k || w ? 1 : -1;
let animationframe = 0;
let callback = () => {
const pos = window.pageyoffset;
window.scroll(0, pos - scrolldistance * scrolldirection);
animationframe = requestanimationframe(callback);
};
animationframe = requestanimationframe(callback);
return () => {
cancelanimationframe(animationframe);
};
}, [arrowup, arrowdown, k, j, w, s]);
return null;
}
Source: stackoverflow.com
Related Query
- React custom scrolling with ArrowKeys
- Infinite scrolling with React JS
- React Router with custom history not working
- FontFamily React Native App overwrite with device custom font (Samsung & Oppo)
- Mocking React custom hook with Jest
- How to create custom React Native components with child nodes
- How to use Material UI custom theme in React with Typescript
- Better aproach for destructing Custom React Hooks with multiple returns?
- React with Material UI not finding custom font
- Access old state to compare with new state inside useEffect react hook with custom hooks usePrevious
- React-leaflet geojson onEachFeature popup with custom react component
- Handling React animation with horizontal scrolling
- Extending react prop-types validation with custom checking
- React Custom Hook with Typescript Type error "Property 'x' does not exist on type 'interface | (({ target }: any) => void)'.ts(2339)"
- React Router with a custom root and a base component
- How to use Material UI custom variants in React with Typescript
- useAsyncStorage custom hook with useState hook in React Native
- Fetch data with a custom React hook
- Custom React renderer with async reconciler methods
- Scrolling to a position in an element on page load with React useEffect
- React Router 4 Optional parameter with custom path
- Custom 'No data' component with dynamic content in React Table
- React Horizontal Scrolling cards with Arrows on top
- React - Material UI - TextField controlled input with custom input component not working properly losing focus
- Adding custom prop to RadioGroup field with React Final Form
- How to wrap all the react examples in styleguidist with a custom theme provider?
- Testing delayed custom React hook with Jest/Enzyme?
- Custom React hook with function as arguments
- Steps to integrate AWS Cognito with both google and custom login with React
- Custom react datepicker with typescript
More Query from same tag
- Using function param in this.refs
- TS2339: Property 'tsReducer' does not exist on type 'DefaultRootState'
- Must specify either a render prop, a render function as children, or a component prop to Field(auto)
- How to route someone to a page when they click a button: React
- How can you return Redirect using React Router?
- Trigger the React-Bootstrap Input Component Validation Programmatically
- React - How do I remove array item from state?
- How to update many records in a collection using firebase?
- component is getting loaded for fraction of second in React
- Forwarding Ref with href from another Component
- useEffect() vs setTimeout() for side effects
- React updating state in two input fields from form submission
- Type checking issues with Redux reducer
- React Router : Dynamically url id
- Antd design - Heap out of memory - webpacker
- How to create a list in react using redux?
- How to add a data attribute to Material-UI Button?
- Is it good practice to pass React Hooks into an utility exported function?
- How do I load a gltf file that has multiple bin and texture files
- Jest test 'unexpected token export'
- Calling a seperate function from within useEffect in react
- Why did adding an extra button to my React Form cause both my buttons to stop working?
- Managing add-to-cart for large quantity of items
- Set Card content visible only on hover with Gatsby + Bootstrap React + scss module
- How do I show a specific web design to a user?
- history.push on form submit
- Can i use multiple state value inside conditional rendering - ReactJs
- styled-components does not style <hr /> element
- How do I reset select elements in a React form after submission?
- react password eye icon for multiple fields