I cant use hooks in securitytextEntry in React native - react-native

This language is React native
export default function forgotPassword(props) {
const [hidePassword, showPassword] = useState(true);
const managePasswordVisibility = () => {
showPassword({ hidePassword: !hidePassword });
};
return (
<View style={styles.textBoxBtnHolder}>
<TextInput
secureTextEntry={hidePassword}
textContentType="password"
style={styles.textBox}
/>
<TouchableOpacity
activeOpacity={0.8}
style={styles.visibilityBtn}
onPress={managePasswordVisibility}
>
<Image
source={
hidePassword
? require("../../assets/icons/hide.png")
: require("../../assets/icons/view.png")
}
style={styles.btnImage}
/>
</TouchableOpacity>
</View>
);
}
i cant able to use hide password in securityTextEntry if i use hooks its showing error and the password is not showing its just hided and its thows a warning .please any one help
failed prop 'secureTextEntry' of type 'object' suppied to 'forwardRef(TextInput) expected boolen

You don't have to use object inside showPassword(), it will only change value of hidePassword so
showPassword(!hidePassword);

Related

react native textinput lost focus after 1 char type

I have this problem with ios but not with android. It only disturb the add task input the task edit and the list name edit. The input addList(It's the one with "What to do?" on the draw) in the header works fine.
UI drawing
Achitecture of components
I console log my component and I can see it rerender everytime I add a letter in the input field.
I checked on google and follow this:(can we link other website here?) https://www.codegrepper.com/code-examples/javascript/react+native+textinput+lost+focus+after+charter+type
Tried the the first solution with onBlurr and onFocus.
I tried to make a TextInput component for add task.
I even try with my component addList but it didn't solve the problem.
Anyone have faced this problem before? Is there anyway to by pass this?
My code without the import/style look like this:
const TaskList: FunctionComponent<TasksListProps> = ({
addTask,
deleteTask,
toggleTask,
editTaskName,
...props
}) => {
console.log('props', props);
const [nameOfTask, setNameOfTask] = useState('');
console.log('name', nameOfTask);
const textHandler = (enteredName: string) => {
setNameOfTask(enteredName);
};
const handleSubmitTask = () => {
if (nameOfTask === '') {
return;
}
addTask(props.listId, nameOfTask);
setNameOfTask('');
};
return (
<View style={styles.tasksListContainer}>
{props.tasks.map(task => (
<SingleTask
key={task.id}
task={task}
listId={props.listId}
deleteTask={deleteTask}
toggleTask={toggleTask}
editTaskName={editTaskName}
/>
))}
<View style={styles.taskInputContainer}>
<TextInput
style={styles.tasksTextInput}
value={nameOfTask}
onChangeText={textHandler}
placeholder="Write a task to do"
/>
<TouchableOpacity onPress={handleSubmitTask}>
<Image source={require('./Img/add-button.png')} />
</TouchableOpacity>
</View>
</View>
);
};
You can create a HOC and wrap your screen width DismissKeyboard
import { Keyboard } from 'react-native';
const DismissKeyboard = ({ children }) => (
<TouchableWithoutFeedback onPress={() => Keyboard.dismiss()}>
{children}
</TouchableWithoutFeedback>
);
That because Re render.
Try to make the input with the main component of the page to test it.
Then check where the error with re-render

Can't figure out why React Hook is invalid

I'm trying to use useContext hook in a React Native page I have, I'm using this hook in other components as well and they work just fine, but this one won't - can't figure out why.
This is my component:
const GoalCard = (goal: IGoal) => {
const {theme} = useContext(ThemeContext); <-- error is here
return (
<Animated.View style={[styles.card, {height: cardHeight, backgroundColor: "#ff5e"}]}>
<View>
.....
</View>
</Animated.View>
);
I'm using this component inside a FlatList which is in a separate file.
return (
<SafeAreaView style={[styles.pageContainer, {backgroundColor: theme.background}]}>
<FlatList
showsVerticalScrollIndicator={false}
style={{padding: 8}}
data={goals}
renderItem={({index}) => GoalCard(goals[index])}
keyExtractor={item => item.id}
/>
</SafeAreaView>
);
I get the error: Invalid hook call, but it does not seem like something is wrong here.
Saw few questions about this, but none worked, also, nothing seems wrong according to the Rules of Hooks page. Why this error happens here?
EDIT:
this is my ThemeProvider:
function ThemeProvider({ children }) {
const [dark, setDark] = React.useState(false);
const toggle = () => {
setDark(!dark);
}
const theme = dark ? themes.dark : themes.light;
return (
<ThemeContext.Provider value={{theme, dark, toggle}}>
{children}
</ThemeContext.Provider>
)
}
And this is my App.tsx:
<ThemeProvider>
<Provider store={store}>
<NavigationContainer>
.....
</NavigationContainer>
</Provider>
</ThemeProvider>

useEffect not working in custom drawer component without refresh

So I am using react-navigation 5 and I have a custom drawer component for my app. I want to display the name of the logged-in user in the drawer for which I am using a state variable and I am updating the state from firestore. I am calling a function in useEffect which accesses firestore and gets the name of the user. But I think the useEffect is not working without refresh because unless I save the project and refresh the application the state is not getting updated in the application and I cannot see the name of the user without refreshing but it is visible after a refresh. Any ideas why this is happening? Any help would be appreciated. Thank you.
Custom drawer
export default function CustomDrawer(props) {
const paperTheme = useTheme();
const [name,setName]=useState('');
useEffect(() => {
doStuff();
}, []);
const doStuff = async () => {
var phone=global.phone;
await firestore().collection("Users").where('Phone Number', '==', phone).get().then(querySnapshot=>{
querySnapshot.forEach(documentSnapshot => {
console.log("in drawer");
console.log(documentSnapshot.data());
setName(documentSnapshot.data().Name);
})
})
};
return(
<View style={{flex:1}}>
<DrawerContentScrollView {...props}>
<View style={styles.drawerContent}>
<View style={styles.userInfoSection}>
<View style={{flexDirection:'row',marginTop: 15}}>
<Avatar.Image
source={{
uri: ''
}}
size={50}
/>
<View style={{marginLeft:15, flexDirection:'column'}}>
<Title style={styles.title}>{name}</Title>
</View>
</View>
</View>
</View>
</DrawerContentScrollView>
</View>
);
}
Looks like you have doStuff function defined outside the useEffects.
Either you need to put it inside useEffects or add it in dependency list
useEffect(() => {
doStuff();
}, [doStuff]);

Entering input causes modal reloading automatically

In my React Native 0.62.3 app, a modal is used to collect user input. Here is the view code:
import { Modal, View, TextInput, Button } from 'react-native';
const [price, setPrice] = useState(0);
const [shippingCost, setShippingCost] = useState(0);
const ReturnModal = () => {
if (isModalVisible) {
return (
<View style={styles.modalContainer}>
<Modal visible={isModalVisible}
animationType = {"slide"}
transparent={false}
onBackdropPress={() => setModalVisible(false)}>
<View style={styles.modal}>
<Text>Enter Price</Text>
<TextInput keyboardType={'number-pad'} onChange={priceChange} value={price} autoFocus={true} placeholder={'Price'} />
<TextInput keyboardType={'number-pad'} onChange={shChange} value={shippingCost} placeholder={'SnH'} />
<View style={{flexDirection:"row"}}>
<Button title="Cancel" style={{bordered:true, backgroundColor:'red'}} onPress={modalCancel} />
<Button title="OK" style={{bordered:true, backgroundColor:'white'}} onPress={modalOk} />
</View>
</View>
</Modal>
</View>
)
} else {
return (null);
}
}
return (
<Container style={styles.container}>
//.....view code
<ReturnModal />
</Container>
)
Here is 2 functions to reset state of price and shippingCost:
const priceChange = (value) => {
if (parseFloat(value)>0) {
setPrice(Math.ceil(parseFloat(value)));
}
};
const shChange = (value) => {
if (parseFloat(value)>=0) {
setShippingCost(Math.ceil(parseFloat(value)));
}
};
The problem is that whenever entering in the price field with keystroke, the modal reloads/resets itself automatically. Tried onChangeText in TextInput and it has the same problem.
It seems like you're declaring your hooks outside your component. Try putting them inside your ReturnModal function instead, like this:
const ReturnModal = () => {
const [price, setPrice] = useState(0);
const [shippingCost, setShippingCost] = useState(0);
...
Documentation reference: Using the State Hook.
Also, I would strongly recommend using the React Hooks ESLint Plugin (among others) to detect issues with your hooks. Here is a guide on how to add this to your React Native project: Add Eslint Support to your React Native Project + React Hooks Rules.
Instead of using animationType = {"slide"} try using animatonType : 'none'

React native onPress with TouchableWithoutFeedback is not working

I am developing a simple React Native application for learning purpose. I am just taking my initial step to get into the React Native world. But in this very early stage, I am having problems. I cannot get a simple touch event working. I am implementing touch event using TouchableWithoutFeedback. This is my code.
class AlbumList extends React.Component {
constructor(props)
{
super(props)
this.state = {
displayList : true
}
}
componentWillMount() {
this.props.fetchAlbums();
}
albumPressed(album)
{
console.log("Touch event triggered")
}
renderAlbumItem = ({item: album}) => {
return (
<TouchableWithoutFeedback onPress={this.albumPressed.bind(this)}>
<Card>
<CardSection>
<Text>{album.artist}</Text>
</CardSection>
<CardSection>
<Text>{album.title}</Text>
</CardSection>
</Card>
</TouchableWithoutFeedback>
)
}
render() {
let list;
if (this.state.displayList) {
list = <FlatList
data={this.props.albums}
renderItem={this.renderAlbumItem}
keyExtractor={(album) => album.title}
/>
}
return (
list
)
}
}
const mapStateToProps = state => {
return state.albumList;
}
const mapDispatchToProps = (dispatch, ownProps) => {
return bindActionCreators({
fetchAlbums : AlbumListActions.fetchAlbums
}, dispatch)
}
export default connect(mapStateToProps, mapDispatchToProps)(AlbumList);
As you can see, I am implementing touch event on the list item. But it is not triggering at all when I click on the card on Simulator. Why? How can I fix it?
You should wrap your content in component like this:
<TouchableWithoutFeedback>
<View>
<Your components...>
</View>
</TouchableWithoutFeedback>
TouchableWithoutFeedback always needs to have child View component. So a component that composes a View isn't enough.
So instead of
<TouchableWithoutFeedback onPressIn={...} onPressOut={...} onPress={...}>
<MyCustomComponent />
</TouchableWithoutFeedback>
use:
<TouchableWithoutFeedback onPressIn={...} onPressOut={...} onPress={...}>
<View>
<MyCustomComponent />
</View>
</TouchableWithoutFeedback>
See the github issue for more info
Can be used with <TouchableOpacity activeOpacity={1.0}> </TouchableOpacity>
For those who struggle with this issue in react-native 0.64, and wrapping it in just a View doesn't work, try this:
<TouchableWithoutFeedback onPress={onPress}>
<View pointerEvents="none">
<Text>Text</Text>
</View>
</TouchableWithoutFeedback>
In my case i accidentally imported TouchableWithoutFeedback from react-native-web instead of react-native. After importing from react-native everything worked as expected.
In more recent React Native versions, just use Pressable instead:
https://reactnative.dev/docs/pressable
In my case, there was a shadow underneath, which caused instability. What I did to solve it was quite simple: zIndex: 65000
<View style={{ zIndex: 65000 }}>
<TouchableWithoutFeedback onPressIn={() => {}>
<View>
</View>
</TouchableWithoutFeedback>
</View>