onValueChange={(itemValue) => {
setSelectedValue(itemValue);
if(itemValue == 'other'){
alert('You Choose: '+itemValue+' Nice')
return(
// The <View> Doesnt Work Why ????
<View style={{backgroundColor:'red',height:5000,width:5000,}}>
<Text>Anas</Text>
</View>
)
}
}}
The Doesnt Work Why ????
i cant put it in if statment or i can ?
i dont hava idea !!
I put together a small sandbox where you can see an example of how to achieve what you want: https://codesandbox.io/s/sad-bird-lzzbb
import React, { useState } from "react";
import { Button, Text, View } from "react-native";
export default function App() {
const [selectValue, setSelectedValue] = useState('');
const onValueChange = (itemValue) => {
setSelectedValue(itemValue);
};
return (
<div className="App">
<Button
onPress={() => onValueChange("other")}
title="Click to set value to 'other'"
/>
{selectValue === "other" ? (
<View style={{ backgroundColor: "red", height: 5000, width: 5000 }}>
<Text>Anas</Text>
</View>
) : null}
</div>
);
}
You can use the onValueChange function to pass it as callback in any event you want (like the onPress of that button I have created) but then you need to return all jsx in the return of your functional component (or the render function if you're using class components)
Related
I created the Text To Speech function in React Native using the react-native-tts library on Android, but it always shows an error/warn like this
new NativeEventEmitter() was called with a non-null argument without the required addListener method.
new NativeEventEmitter() was called with a non-null argument without the required removeListeners method.
Here's an example from my code.
import React from 'react';
import MaterialCommunityIcons from 'react-native-vector-icons/MaterialCommunityIcons';
import {View, Text, SafeAreaView, TouchableOpacity} from 'react-native';
import Tts from 'react-native-tts';
const TextToVoiceScreen = ({route, navigation}) => {
const handleTextToSpeech = val => {
let stringSpace = val.split('').join(' ');
// Set Engine Voice
Tts.setDefaultEngine('com.google.android.tts');
Tts.getInitStatus().then(
() => {
Tts.stop();
Tts.setDucking(true);
Tts.setDefaultRate(0.09);
Tts.speak(stringSpace, {
androidParams: {
KEY_PARAM_PAN: -1,
KEY_PARAM_VOLUME: 0.9,
KEY_PARAM_STREAM: 'STREAM_MUSIC',
},
});
},
err => {
if (err.code === 'no_engine') {
Tts.requestInstallEngine();
console.log('Install Engine');
}
},
);
};
return (
<SafeAreaView>
<View>
<Text>Test Voice</Text>
<TouchableOpacity onPress={() => handleTextToSpeech('Hello World')}>
<View>
<MaterialCommunityIcons
name="text-to-speech"
color={'#33691e'}
size={20}
/>
</View>
</TouchableOpacity>
</View>
</SafeAreaView>
);
};
export default TextToVoiceScreen;
this is so annoying.
how fix this issues guys..
I am using a so simple GiftedChat component in react native on expo, the problem here is when i open the first time the keyboard this works fine, but the second time i press in the textInput but the keyboard doesn't appear, i'm using a emulator of android 5 and a device with android 7. Doesn't work in any
import { useState, useLayoutEffect, useCallback } from 'react'
import { TouchableOpacity } from 'react-native'
import { GiftedChat } from 'react-native-gifted-chat'
import {
collection,
addDoc,
orderBy,
query,
onSnapshot
} from 'firebase/firestore'
import { signOut } from 'firebase/auth'
import { auth, database } from '../config/firebase'
import { useNavigation } from '#react-navigation/native'
import { AntDesign } from '#expo/vector-icons'
import colors from '../colors'
export default function Chat() {
const [messages, setMessages] = useState([])
const navigation = useNavigation()
const onSignOut = () => {
signOut(auth)
.catch(err => console.log('Error logging out: ', err.message))
}
useLayoutEffect(() => {
navigation.setOptions({
headerRight: () => (
<TouchableOpacity
style={{
marginRight: 10
}}
onPress={onSignOut}
>
<AntDesign
name='logout'
size={24}
color={colors.gray}
style={{
marginRight: 10
}}
/>
</TouchableOpacity>
)
})
}, [navigation])
useLayoutEffect(() => {
const collectionRef = collection(database, 'chats')
const q = query(collectionRef, orderBy('createdAt', 'desc'));
const unsubscribe = onSnapshot(q, snapshot => {
setMessages(
snapshot.docs.map(doc => ({
_id: doc.data()._id,
createdAt: doc.data().createdAt.toDate(),
user: doc.data().user,
text: doc.data().text
}))
)
})
return unsubscribe
}, [])
const onSend = useCallback((messages = []) => {
setMessages(previewMessages => GiftedChat.append(previewMessages, messages))
const { _id, createdAt, text, user } = messages[0]
addDoc(collection(database, 'chats'), {
_id,
createdAt,
text,
user,
})
}, [])
return (
<>
<GiftedChat
messages={messages}
showAvatarForEveryMessage={false}
showUserAvatar={true}
onSend={message => onSend(message)}
messagesContainerStyle={{
backgroundColor: '#fff'
}}
user={{
_id: auth?.currentUser?.email,
avatar: 'https://placeimg.com/140/140/any'
}}
/>
</>
)
}
gif example of the error
If you can help me with the reason why this happens i will thank you so much...
The problem is that the TextInput of GiftedChat (of TextInput in general actually) never looses focus if you dismiss the keyboard using the virtual Android button. Thus, the keyboard is not opened again if you simply retouch into the TextInput. If you touch outside it and then inside again, you will notice that the keyboard opens again. This should be the normal behavior of any TextInput and might be even expected by the user (we can open the keyboard again by pressing the same button).
However, you could try to handle this programmatically as well. The GiftedChat component provides a function to allow you to refocus the TextInput again programmatically. It is called focusTextInput() and it
Open(s) the keyboard and focus the text input box
const ref = useRef(null)
<GiftedChat
…
ref={ref}
/>
Then, call ref.focusTextInput(). We could then wrap the GiftedChat component inside a Pressable and fire this in the onPress function.
const ref = useRef(null)
<Pressable onPress={() => ref.focusTextInput()}
<GiftedChat
…
ref={ref}
/>
</Pressable>
I am attempting to build a notification service I can use within React Navigation; how far I have gotten in this:
Now this is a modal, that the card element has been hidden and then the view style has been filled into only 15% at the top of the element, and the element will react if you click out of the white area of the notification.
Here is the code for the NotificationModal:
import React from 'react';
import { View, TouchableHighlight,TouchableWithoutFeedback } from 'react-native';
import { Text } from 'react-native-elements';
export default class NotificationModal extends React.Component {
static navigationOptions = ({ navigation }) => {
const title = navigation.getParam('title','No item found...');
return {
title: title
};
};
constructor(props) {
super(props);
}
componentDidMount() {
console.log(this.props);
}
render() {
const { navigation } = this.props;
let title = navigation.getParam('title', '');
return (
<TouchableWithoutFeedback>
<View style={{ flex: 1 ,flexDirection: 'column', justifyContent: 'flex-start'}}>
<View style={{ height: "15%" ,width: '100%', backgroundColor:"#fff", justifyContent:"center"}}>
<Text style={{fontSize:25}}>{title}xd</Text>
</View>
<TouchableHighlight onPress={() => { this.props.navigation.goBack(); }} style={{backgroundColor: "rgba(0,0,0,0)"}}>
<View style={{ height: "85%" ,width: '100%', backgroundColor: "rgba(0,0,0,0)", justifyContent:"center"}}>
<View>
</View>
</View>
</TouchableHighlight>
</View>
</TouchableWithoutFeedback>
);
}
}
At at my root navigation stack it looks like this:
export default RootStack = createStackNavigator(
{
Main: {
screen: MainStack,
},
QuickStockModal: {
screen: StockModal,
},
NotificationModal: {
screen: NotificationModal,
}
},
{
mode: 'modal',
headerMode: 'none',
cardStyle:{
backgroundColor:"transparent",
opacity:0.99
}
}
);
Finally I call this pseudo notification modal like any other navigation instance:
this.props.navigation.navigate('NotificationModal', {
title: 'test'
});
Problems with this
It wont just act as a quick update, it will overtake the touch area, I just wish to let the user know things like 'search results empty' or 'barcode invalid' etc, without hijacking the touch. (But being able to touch buttons of the notification within the white area thats visible)
When you press the outside area to dismiss it, the 'dismiss area' turns dark as it disappears, this looks bad, I am hoping to change the animation to simply push up instead of down and hopefully avoid this
this is a messy way to do notifications but other manners will complicate my current app design too much (Using Redux for instance, will be alot of work for simply trying to add in-app notifications)
In-app notification libs arent customizable enough and also dont even work properly sadly
I am trying to use react-native-sidemenu https://github.com/react-native-community/react-native-side-menu
My code looks like this.
There is no error and even output is overlapping to each other
var list = [{name: "komaldeep", subtitle: "dssdfds", avatar_url:"sadasdsa" }];
export default class First extends Component {
constructor(props) {
super(props);
this.state = {
isOpen: false,
};
this.toggleSideMenu = this.toggleSideMenu.bind(this);
}
toggleSideMenu () {
this.setState({
isOpen: !this.state.isOpen
})
}
render() {
//menu list `enter code here`
const MenuComponent = (
<View style={{flex: 1, backgroundColor: '#ededed', paddingTop: 200}}>
<List containerStyle={{marginBottom: 20}}>
{
list.map((l, i) => (
<ListItem
roundAvatar
onPress={() => console.log('Pressed')}
avatar={l.avatar_url}
key={i}
title={l.name}
subtitle={l.subtitle}
/>
))
}
</List>
</View>
)
return (
<SideMenu
isOpen={this.state.isOpen}
menu={MenuComponent} >
//Menu Component just contain some random text
<Menu toggleSideMenu={this.toggleSideMenu.bind(this)}/>
</SideMenu>
);
}
}
Can you just guide me.. what i am doing wrong..
OutPut looks like this
enter image description here
The reason that the items in your menu shows up on the right of the screen, seemingly outside of the menu, is that your MenuComponent takes up the entire screen. Set the prop openMenuOffset={number} to SideMenu and use the same number to set width: number in the style of your MenuComponent.
I would like to have an input that updates continuously as the user types and then loses focus. The feedback will be a border around the input.
1 Green: when valid
2 Amber: when typing and is in error state (Green when valid)
3 Red: when in error state and unfocused
4 Nothing: when input is pristine (not touched and empty)
What is the best way to achieve this?
Ideally this will work with both iOS and Android.
TextInput has two functions that will be useful to achieve this:
onBlur and onChangeText
To dynamically set the style on the TextInput, you could attach a variable for the bordercolor like below:
<TextInput
onBlur={ () => this.onBlur() }
onChangeText={ (text) => this.onChange(text) }
style={{ borderColor: this.state.inputBorder, height: 70, backgroundColor: "#ededed", borderWidth: 1 }} />
Then, pass the result from the onChangeText function through a regex or pattern matcher to achieve whatever result you are trying to achieve.
I've set up a working project here that checks if there is whitespace, and throws the errors you are wanting. You can take it and edit it to be more specific to your needs, but the basic premise should work the same. I've also put the code below for the working project that implements the functionality:
'use strict';
var React = require('react-native');
var {
AppRegistry,
StyleSheet,
Text,
View,
TextInput
} = React;
var SampleApp = React.createClass({
getInitialState: function() {
return {
inputBorder: '#eded',
defaultVal: ''
}
},
onBlur: function() {
console.log('this.state.defaultVal', this.state.defaultVal)
if(this.state.defaultVal.indexOf(' ') >= 0) {
this.setState({
inputBorder: 'red'
})
}
},
onChange: function(text) {
this.setState({
defaultVal: text
})
if(text.indexOf(' ') >= 0) {
this.setState({
inputBorder: '##FFC200'
})
} else {
this.setState({
inputBorder: 'green'
})
}
},
render: function() {
return (
<View style={styles.container}>
<View style={{marginTop:100}}>
<TextInput
onBlur={ () => this.onBlur() }
onChangeText={ (text) => this.onChange(text) }
style={{ height: 70, backgroundColor: "#ededed", borderWidth: 1, borderColor: this.state.inputBorder }} />
</View>
<View style={{marginTop:30}}>
<TextInput
style={{ height: 70, backgroundColor: "#ededed" }} />
</View>
</View>
);
}
});
var styles = StyleSheet.create({
container: {
flex: 1,
}
});
AppRegistry.registerComponent('SampleApp', () => SampleApp);