react-native-community / hooks Goto Github PK
View Code? Open in Web Editor NEWReact Native APIs turned into React Hooks for use in functional React components
License: ISC License
React Native APIs turned into React Hooks for use in functional React components
License: ISC License
Currently, useDeviceOrientation
only tells us "landscape" or "portrait". But devices actually have four orientations, not two -- portrait up, portrait down, landscape left, and landscape right. It would be very useful if the hook could support all device orientations.
Hi All,
I am trying to yarn installl react-native community hooks and its still not installing. I don't know why. Here is a error log added in this statement as suggested.
大佬,删除一个库:https://github.com/ke2933/demo
我们公司查代码,涉及前端源码泄露,可以删除不?
const keyboard = useKeyboard()
this hook cause re-render all component too many on keyboard show and dismiss
after remove it, my app is working properly not re-render on keyboard show and hide
it work fine in android but not work in iOS
could you fixed this hook.
thank you very much
I think it would be nice if useKeyboard
could return an Animated.value
for the keyboard height.
Currently, when using keyboardHeight
to set e.g. padding it looks very janky when the keyboard is shown or hidden. Exporting an animated value that represents the height could allos the end user to animate the padding as the keyboard appears.
t.b.d
t.b.d.
I need this in a project I'm working on so I will probably submit a pull request as soon as I get time
import { useCameraRoll } from '@react-native-community/hooks'
const [photos, getPhotos, saveToCameraRoll] = useCameraRoll()
{
photos.map((photo, index) => /* render photos */)
}
<Button title='Get Photos' onPress={() => getPhotos()}>Get Photos</Button>
Initial values returned by this hook can be incorrect based od how was app started and when hook mounted.
Example:
App is started in portrait
, then orientation is chaged to landscape
and after that this hook is mounted. It will show that device is in landscape.
Not sure if this is by design or it's a bug.
My current solution looks like this:
function getDimensions() {
return Dimensions.get("screen");
}
...
function useMyDeviceOrientation() {
...
const [orientation, setOrientation] = useState({
portrait: isOrientationPortrait(getDimensions()),
landscape: isOrientationLandscape(getDimensions()),
});
...
}
I am not able to find useDimensions
on latest version 3.0.0
. Why this was removed? Actually the problem is useWindowDimesions
fron RN doesn't send correct width and height when Alert is open on IOS. So can we revert back the removal of useDimensions? I am currently using 2.8.0 in the mean while
ListScreen
, I click the android backbutton, although I can back to the previous screen,Alert
defined in RootScreen
will always pop up.DetailScreen
back directly to RootScreen
.Screen Tree
-RootScreen
-ListScreen
-DetailScreen
root.screen.js
import { useBackHandler } from "@react-native-community/hooks"
const RootScreen = () => {
const backActionHandler = () => {
Alert.alert('Wait a moment', 'Are you sure to exit the app?', [
{
text: 'go on',
onPress: () => null,
style: 'cancel',
},
{ text: 'OK to exit', onPress: () => BackHandler.exitApp() },
]);
return true;
};
useBackHandler(backActionHandler)
return (
<View>...</View>
)
}
list.screen.js
import { useBackHandler } from "@react-native-community/hooks"
const ListScreen = ({ navigation: { goBack }) => {
useBackHandler(goBack)
return (
<View>...</View>
)
}
detail.screen.js
const DetailScreen = () => {
return (
<View>...</View>
)
}
//or
import { useBackHandler } from "@react-native-community/hooks"
const DetailScreen = ({navigation:{goBack}}) => {
useBackHandler(goBack)
return (
<View>...</View>
)
}
Version Info
"@react-native-community/hooks": "^2.6.0",
"@react-navigation/native": "^5.9.2",
"@react-navigation/stack": "^5.14.2",
Apparently this has broken. auto
is not releasing with PR merges anymore. We should fix that.
EventEmitter.removeListener('appStateDidChange', ...): Method has been deprecated. Please instead use remove() on the subscription returned by EventEmitter.addListener.
keyboardHidden
method to keyboardWillShow
event?I see many people on YouTube tutorials using this specific hook but I can't import it, did y'all remove it by any chance? And if so how can I replicate the same thing with a different hook?
some times we need to have previous state to make sure preious state was 'background' or 'inactive' and currentstate is active, so we will call a method. but currently the only state it returns is currentState.
It would be useful. One thing to think about for this, is how we determine the version number. When and how do we bump patch, minor, major. Automatic, based on the labels of a PR to be merged? Maybe based on git tags? Maybe manual change on package.json and that triggers a release? 🤔
We can check https://github.com/react-native-community/react-native-webview/blob/master/.circleci/config.yml
When a component uses useKeyboard()
and this component is mounted while the keyboard is open, useKeyboard().keyboardShown
returns false.
The background is we have a sticky button at the bottom on multiple screens. This button should not be displayed when the keyboard is open, since it takes away too much space. In one of those screens we only show the button after an text-input is made. At this point the keyboard is open and the button is shown because of the error above.
When the maintainers create a new PR in this repo, a canary release happens. When anyone else creates a PR, it's a fork, so the release doesn't happen.
It would be very useful though. I'm making this issue so we can maybe find a way.
The lib
folder is not included in the npm release.
From React Native v0.61, useWindowDimensions
has been implemented to the core repository facebook/react-native@5ec382d#diff-d22b00f3f4e10cfb3e6ac4e653bcebd7R17
This is essentially the same functionality as useDimensions
in this repo.
Should useDimensions
be removed from this package? or should it continue to exist for RN 0.59, and 0.60 users?
New to Development, trying to learn React Native but having an issue when trying to install Hooks. Using Expo Go, which is also showing an issue, says Index.js doesn't exist for hooks. I've already installed Hooks using NPM.
This is my code:
import { StatusBar } from 'expo-status-bar';
import { StyleSheet, Text, View, Image, SafeAreaView, Button, Alert, Dimensions } from 'react-native';
import { useDeviceOrientation } from '@react-native-community/hooks'
export default function App() {
const orientation = useDeviceOrientation()
console.log('is orientation portrait: ', orientation.portrait)
console.log('is orientation landscape: ', orientation.landscape)
const handleButtonPress = () => {
Alert.prompt("Title", "This is my message", text => console.log(text))
}
return (
<SafeAreaView style={styles.container}>
<Button
onPress={handleButtonPress}
title={"Press me!"}
/>
<Text>Hello!</Text>
<StatusBar style="auto" />
</SafeAreaView>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#f1f1f1',
alignItems: "center",
justifyContent: "center",
},
});
With reference to the documentation of https://reactnative.dev/docs/interactionmanager
The method runAfterInteractions
returns a cancellable promise, which has a cancel method, was wondering if this cancel method should be applied on component clean up.
https://github.com/react-native-community/hooks/blob/master/src/useInteractionManager.ts#L8
import {useEffect, useState, useRef} from 'react'
import {InteractionManager} from 'react-native'
export function useInteractionManager() {
const [complete, updateInteractionStatus] = useState(false)
const interactionHandler = useRef();
useEffect(() => {
interactionHandler.current = InteractionManager.runAfterInteractions(() => {
updateInteractionStatus(true)
})
return () => interactionHandler.current & interactionHandler.current.cancel()
}, [interactionHandler])
return complete
}
For some reason I get this error when just calling useAppState in my function, that already has many other hooks
This is the code that runs it, its a child component somewhere, but it runs the code without the useAppState() line. I even added a copy of useAppState in my utils folder and it works.
import React, { useEffect, useState } from 'react';
import { useAppState } from 'react-native-hooks';
import PhoneStatus from '../../containers/phone-status';
import AuthService from '../../services/auth';
import WithoutWallet from './without-wallet';
const onAppFocusChanges = ({ linkingInitialized, setLinkingInitialized }) => {
if (linkingInitialized) {
setTimeout(() => {
setLinkingInitialized(false);
}, 10000);
}
};
export default () => {
const currentAppState = useAppState();
const [linkingInitialized, setLinkingInitialized] = useState(false);
const phoneStatus = PhoneStatus.useContainer();
const authService = AuthService.useContainer();
const { hasWallet } = phoneStatus;
const { currentUser } = authService;
useEffect(() => {
phoneStatus.checkForWallet();
}, []);
console.log(hasWallet);
if (hasWallet) {
return <WithoutWallet />;
}
return <></>;
};
Does this maybe have to do that the react dependency is not a peer dependency stated here: https://reactjs.org/warnings/invalid-hook-call-warning.html#duplicate-react
React native info output:
info
React Native Environment Info:
System:
OS: macOS 10.14.6
CPU: (8) x64 Intel(R) Core(TM) i7-7920HQ CPU @ 3.10GHz
Memory: 310.77 MB / 16.00 GB
Shell: 5.3 - /bin/zsh
Binaries:
Node: 9.10.0 - ~/.nvm/versions/node/v9.10.0/bin/node
Yarn: 1.15.2 - ~/.yarn/bin/yarn
npm: 6.4.0 - ~/.nvm/versions/node/v9.10.0/bin/npm
Watchman: 4.9.0 - /usr/local/bin/watchman
SDKs:
iOS SDK:
Platforms: iOS 12.4, macOS 10.14, tvOS 12.4, watchOS 5.3
Android SDK:
API Levels: 23, 25, 26, 27, 28
Build Tools: 23.0.1, 26.0.2, 27.0.3, 28.0.0, 28.0.3
System Images: android-28 | Google Play Intel x86 Atom
IDEs:
Android Studio: 3.1 AI-173.4819257
Xcode: 10.3/10G8 - /usr/bin/xcodebuild
Version number: "react-native": "^0.59.3"
Which resolves now to "0.59.10"
Describe what you expected to happen:
All the stuff inside that code example is non relateable. And as stated, i copied the code and added a utils/hooks/useAppState and that worked fine. So there is something with loading this lib in.
Hello there,
I am using the height value from useWindowDimensions in Expo.
I am on an iPhone 10 so height is 812, most of the time. But there are sometimes where the hook returns 70 instead of 812.
const { height } = useWindowDimensions();
const { bottom, top } = useSafeAreaInsets();
const bottomOffset = height - bottom - 40;
console.log(`${height} - ${bottom} - 40 = ${bottomOffset}`);
Working result is "812 - 34 - 40 = 738" and sometimes I have "70 - 34 - 40 = -4".
Does somebody know about this?
Thanks.
Many APIs are now deprecated by facebook.
See for example:
https://facebook.github.io/react-native/docs/netinfo
How should we handle this? peerDependencies?
Excuse me for the words but I just looked around the hooks and saw so many bad practices in your project (mostly about performance) so I wonder whether you still maintain this project or not.
For example, this hook does resubscribe event every time the component renders. There is a fix here but for maybe some reasons it is merged yet: #38
src/useAppState.ts
import React, { useEffect, useState } from 'react'
import { AppState, AppStateStatus } from 'react-native'
export default function useAppState() {
const currentState = AppState.currentState
const [appState, setAppState] = useState(currentState)
function onChange(newState: AppStateStatus) {
setAppState(newState)
}
useEffect(() => {
AppState.addEventListener('change', onChange)
return () => {
AppState.removeEventListener('change', onChange)
}
})
return appState
}
This hook creates new getPhotos
and saveToCameraRoll
functions every time the hook is called. It would cause the hook consumer component to rerender unexpectedly.
src/useCameraRoll.ts
export default function useCameraRoll() {
const [photos, setPhotos] = useState(initialState)
async function getPhotos(config = defaultConfig) {
try {
const photos = await CameraRoll.getPhotos(config)
setPhotos(photos)
} catch (err) {
console.log('error: ', err)
}
}
async function saveToCameraRoll(tag: string, type?: 'photo' | 'video') {
try {
await CameraRoll.saveToCameraRoll(tag, type)
} catch (err) {
console.log('error saving to camera roll: ', err)
}
}
return [photos, getPhotos, saveToCameraRoll]
}
This issue lists Renovate updates and detected dependencies. Read the Dependency Dashboard docs to learn more.
These updates are currently rate-limited. Click on a checkbox below to force their creation now.
@types/react
, react
, react-test-renderer
)These updates have all been created already. Click a checkbox below to force a retry/rebase of any.
react-native
, @types/react-native
).github/workflows/publish-canary.yml
actions/checkout v3
actions/setup-node v3
.github/workflows/release.yml
actions/checkout v3
actions/setup-node v3
package.json
@auto-it/all-contributors 10.46.0
@auto-it/first-time-contributor 10.46.0
@react-native-community/eslint-config 3.2.0
@testing-library/react-hooks 8.0.1
@testing-library/react-native 12.1.3
@types/jest 29.5.3
@types/react 18.2.20
@types/react-native 0.72.2
all-contributors-cli 6.25.1
auto 10.46.0
eslint 8.41.0
eslint-plugin-prettier 4.2.1
jest 29.5.0
prettier 2.8.8
react 18.2.0
react-native 0.71.12
react-test-renderer 18.2.0
ts-jest 29.1.1
typescript 5.0.4
react >=17.0.2
react-native >=0.65
react-native info
output:
# "react-native": "^0.63.2",
Library version: ^2.6.0
orientation.landscape is always false when change orientation
In current implementation we just ignore errors. In some cases we need access to error.
I guess we need add error in hooks response to avoid breaking changes later.
What do you think about it ?
Example:
import { useGeolocation } from 'react-native-hooks'
const [position, stopObserving, setRNConfiguration, error] = useGeolocation()
console.log('latitude: ', position.coords.latitude)
console.log('error: ', error)
Hi, it seems like no license is attached to this repo yet. This would imply exclusive copyright by default, as stated here.
Assuming this is just an oversight, a license should probably be added to avoid any doubt that this repo is open source.
I just upgraded to RN 0.65.1 and didn't have this problem before but this is also the only library I'm having this issue with.
When I change something in the file and Fast Refresh reloads the file I get the following error where it appears that upon reload react-native
is no longer loaded on the unmount in node_modules/@react-native-community/hooks/lib/useKeyboard.js
.
There's currently no index.d.ts file or corresponding @types/react-native-hooks
available.
Firstly thank you for the fine work!
TIL there is a thing called "floating keyboard" for iPad. You can enable it by pinching on the keyboard on iPad and disable it by un-pinching(?).
keyboardShown
and keyboardHeight
seem to misbehave when this is active and when you dismiss it.
Using the following code for the scenarios below:
const { keyboardShown, keyboardHeight } = useKeyboard();
console.log('keyboardHeight: ', keyboardHeight);
console.log('keyboardShown: ', keyboardShown);
When Floating Keyboard is open from the start (maybe you already set this in another app), it logs:
LOG keyboardHeight: 0
LOG keyboardShown: false
And then when you swipe to remove the floating keyboard and replace it with the regular keyboard, it logs (this is good):
LOG keyboardHeight: 337
LOG keyboardShown: true
And then, pinch to enable the floating keyboard again, and it logs (this is bad):
LOG keyboardHeight: 337
LOG keyboardShown: false
It seems like at the very least, keyboardHeight
should be set to 0 on the last scenario. That way you can inform the your KeyboardAvoidingView to be enabled={false}
. That is how I discovered the issue.
There is a decent answer here about detecting the floating keyboard. Perhaps some additional fields could be added to the hook to make it more useful.
keyboardWillShow & keyboardWillHide is not available on Android.
See: https://facebook.github.io/react-native/docs/keyboard
One idea is to listen to those + keyboardDidShow & keyboardDidHide (these are available on Android).
Would that be a feasible solution or will it mess something up?
AppStateStatus
should be a enum and export, it's better for stability, using with the useAppState hook and avoids having to manually create enums for app states which could potentially change in the future leading to more issues.
If this is accepted I can create a PR for it.
Clipboard is deprecated and when you use a the useClipboard
hook you'll see a warning !
We should try with @react-native-clipboard/clipboard
lib
Do you have any ideas on how to support the next hooks as they are deprecated or removed?
Shell we will mark them as @deprecated
too (using comments), or add info in the README file?
useCameraRoll
CameraRoll
was removed in React Native 0.61.x
useClipboard
Clipboard
marker as deprecated, but not deleted yet (see master)
After the keyboard closes, the height isn't updated.
Looking at the source code, if the event exists it does not set the height.
See: https://github.com/react-native-community/hooks/blob/master/src/useKeyboard.ts#L36
Library version: 2.5.1
P.s. Closing as I am seeing this on a simulator, will check this on a real device and reopen if needed.
I use useKeyboard hook, and when the keyboard is closing I got an error null is not an object (evaluating e.endCoordinates)
.
React native info output:
info
React Native Environment Info:
System:
OS: Windows 10
CPU: (4) x64 Intel(R) Core(TM) i7-7500U CPU @ 2.70GHz
Memory: 5.21 GB / 15.88 GB
Binaries:
Yarn: 1.16.0 - C:\Users\David\Projects\WI\personalized-nutrition-app\node_modules\.bin\yarn.CMD
npm: 6.5.0 - C:\Program Files\nodejs\npm.CMD
IDEs:
Android Studio: Version 3.0.0.0 AI-171.4408382
Done in 3.07s.
Library version: 0.9.0
Describe what you expected to happen:
import { useKeyboard } from 'react-native-hooks'
...
const { isKeyboardShow } = useKeyboard()
return (
{!isKeyboardShow && Test useKeyboard}
</View>
)
Instead of writing endCoordinates: e.endCoordinates,
write endCoordinates: e ? e.endCoordinates : null,
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.