Modal not displaying in react-native? - view

Hey guys i am trying to show modal on click of map marker but i fail to see any modal on marker click can anybody help me out what is the issue. I am using Modal from https://github.com/maxs15/react-native-modalbox
Here is the code:
import Modal from "react-native-modalbox";
export default class App {
openModal4(id) {
this.refs.modal4.open();
}
render() {
return (
<View style={style.mainContainer}>
<MapView
ref="map"
showUserLocation={true}
region={this.state.region}
onRegionChange={this.onRegionChange}
onRegionChangeComplete={this.onRegionChangeComplete}
style={styles.map}
rotateEnabled={false}
showsCompass={false}
>
{this.state.markers.map(function(marker) {
return (
<MapView.Marker
coordinate={marker.latlng}
key={marker.id}
onPress={this.openModal4}
/>
);
})}
</MapView>
<View
style={{
position: "absolute",
width: windowsWidth,
height: windowsHeight - 100,
alignItems: "center",
justifyContent: "center"
}}
>
<Image source={require("./assets/map-marker.png")} />
</View>
<Modal
style={[styles.modal, styles.modal4]}
position={"bottom"}
ref={"modal4"}
/>
</View>
);
}
}
can anybody help me out? Thanks in advance.

You should make changes, to bind this in callbacks
read this article Don't Use Bind When Passing Props
openModal4 = (id) => {
this.refs.modal4.open();
}

Guys Binding was the issue which gets solved after using arrow function =>
here is the code
openModal4(id){
this.refs.modal4.open();
}
{this.state.markers.map((marker) => {
return(
<MapView.Marker coordinate={marker.latlng} key={marker.id} onPress={this.openModal4} />
);
})}
And you need to bind the function in constructor as it consist of 'this'
this.openModal4 = this.openModal4.bind(this)
hope my struggle would help others

Related

React navigation custom header doesn't disappear when navigating away from screen (iOS only)

I have a stack navigator where one of the screen uses a custom header:
import { createStackNavigator } from "#react-navigation/stack";
import * as React from "react";
import { Button, View } from "react-native";
const Stack = createStackNavigator();
function ScreenA({ navigation }) {
return (
<View style={{ flex: 1, justifyContent: "center"}}>
<Button title="Click me" onPress={() => navigation.navigate("ScreenB")} />
</View>
);
}
function ScreenB({ navigation }) {
return (
<View style={{ flex: 1 , justifyContent: "center"}}>
<Button title="Click me" onPress={() => navigation.navigate("ScreenA")} />
</View>
);
}
function TestComp() {
return (
<Stack.Navigator>
<Stack.Screen
name="ScreenA"
component={ScreenA}
options={{ header: () => <View style={{ height: 160, backgroundColor: "red" }}></View> }}
/>
<Stack.Screen name="ScreenB" component={ScreenB} />
</Stack.Navigator>
);
}
export default TestComp;
As a result, the header of ScreenA (a red bar) is visible from ScreenB. This doesn't happen on Android where the header is properly shown ONLY on ScreenA.
How can I stop the header from ScreenA from showing on ScreenB?
Solved it by using <Stack.Navigator headerMode="screen"> !

Replace with a text while encountering onError on Image REACT NATIVE

Just like HTML, we have the opportunity to show a text i.e.
<img src="hello.png" alt="hello" />
There is plenty of suggestions for replacing an image with another image (fallback src), but I need to show a text instead of any other images!
React Native Image onError method will execute on Image when image not found on server or unexpectedly something wrong goes with the connection. Using that you can display text as below,
import React, { Component } from "react";
import { Text, View, Image, StyleSheet } from "react-native";
export default class Example extends Component {
state = {
isLoadingImage: true,
isImageFailed: false
};
onErrorLoadingImage = () => {
this.setState({
isLoadingImage: false,
isImageFailed: true
});
};
render() {
return (
<View style={styles.container}>
{!this.state.isImageFailed ? (
<Image
source={{
uri:
"https://reactnativecode.com/wp-content/uploads/2017/10/Guitar.jpg"
}}
style={styles.imageStyle}
onError={this.onErrorLoadingImage}
/>
) : (
<View style={styles.container}>
<Text>Error loading image</Text>
</View>
)}
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
padding: 10,
justifyContent: "center",
alignItems: "center"
},
imageStyle: {
resizeMode: "center",
width: "50%",
height: "50%"
}
});
Unfortunately, there is no other way to display text just like HTML alt=" Error loading image "
Hope this will help you.

React-Native | ScrollView right to left

I've got a simple ScrollView:
<ScrollView
style={$style.category_container}
horizontal={true}
showsHorizontalScrollIndicator={false}
automaticallyAdjustContentInsets={true}
>
<Item title={'1'} />
<Item title={'2'} />
</ScrollView>
Item is a component that loads several thumbnails. My application is planned for both LTR and RTL users, so there is a change in directions for RTL.
The problem is when I'm using the RTL interface - the ScrollView is still moving from left to right, and I can't see all my thumbnails.
How can I solve it?
If someone will run into this in the future:
There isn't any 'built-in' property that will set ScrollView's direction to RTL at the moment.
However That's what worked for me:
set flexDirection: 'row-reverse' to ScrollView's style, which will order your items from right to left.
use onContentSizeChange to init list's scroll on the right side.
Here's an example:
scrollListToStart(contentWidth, contentHeight) {
if (I18nManager.isRTL) {
this.scrollView.scrollTo({x: contentWidth});
}
}
render() {
let containerStyle = I18nManager.isRTL ? styles.RTLContainer : styles.LTRContainer;
return (
<ScrollView
ref={ref => this.scrollView = ref}
onContentSizeChange={this.scrollListToStart.bind(this)}
horizontal={true}
style={[styles.buttonsContainer, containerStyle]}>
{this.renderButtons()}
</ScrollView>
)
}
const styles = StyleSheet.create({
RTLContainer: {
flexDirection: 'row-reverse'
},
LTRContainer: {
flexDirection: 'row'
}
})
you can use this way
i did this and worked for me
This solution has 2 rounds
1-first make this style for your scrollView : style={{scaleX:-1}}
2-second make this style for each of your childs in scrollView : style={{scaleX:-1}}
For Example
<ScrollView
horizontal={true}
contentContainerStyle={{height: 65}}
style={{scaleX:-1}}
showsHorizontalScrollIndicator={false}>
{
data.sports.map((data,index) => {
return(
<View key={index}
style={{width:150,height:55,backgroundColor:'yellow', marginHorizontal:4,scaleX:-1}}/>
)
})
}
</ScrollView>
As you can see my scrollview has scaleX = -1 style
Also all of my childs in scrollView has scaleX = -1 style
as scaleX is deprecated in views you can use transform:[{rotateY:'180deg'}] instead
Just in case someone has a similar problem to mine. I was doing a horizontal ScrollView with user images and needed the images to appear from right to left. Thank you Mr-Ash & Sergey Serduk for getting me there.
<ScrollView
horizontal
showsHorizontalScrollIndicator={false}
style={{
alignSelf: "center",
borderRadius: 100,
transform: [{ scaleX: -1 }],
}}>
{users.map((user, i) => {
return (
<View key={i} style={[{ transform: [{ scaleX: -1 }], zIndex: 100 - i }]}>
<UserImage leftMargin={-27} />
</View>
);
})}
<View style={{ marginRight: 27 }} />
</ScrollView>
In my case a proper solution is wrapping a <ScrollView/> component with <View/> see below:
<View style={{direction: 'rtl'}}><ScrollView ... /></View>
Direction can be set as rtl, ltr, inherit, initial, revert or unset
The best possible solution for RTL ScrollView is the combination of scrolling it to the end and flex-direction: 'row-reverse'
const scrollRef = useRef<any>();
const scrollToEnd = () => {
scrollRef.current.scrollToEnd({ animated: false });
};
<ScrollView
contentContainerStyle={{
flexDirection: "row-reverse"
}}
onContentSizeChange={scrollToEnd}
ref={scrollRefOne}
horizontal
showsHorizontalScrollIndicator={false}
>
...
</ScrollView>

React-Native refs undefined on text input

we are currently running React-Native 0.33
We are trying to use the refs to go from 1 text input to another when they hit the next button. Classic username to password.
Anyone have any idea? Below is the code we are using. From other posts I've found on stack this is what they've done; however, it's telling us that this.refs is undefined.
UPDATE
So I've narrowed the problem down to
render() {
return (
<Navigator
renderScene={this.renderScene.bind(this)}
navigator={this.props.navigator}
navigationBar={
<Navigator.NavigationBar style={{backgroundColor: 'transparent'}}
routeMapper={NavigationBarRouteMapper} />
} />
);
}
If I just render the code below in the renderScene function inside of the original render it works, however with the navigator it won't work. Does anyone know why? Or how to have the navigator show as well as render the code in renderScene to appear in the original render?
class LoginIOS extends Component{
constructor(props) {
super(props);
this.state={
username: '',
password: '',
myKey: '',
};
}
render() {
return (
<Navigator
renderScene={this.renderScene.bind(this)}
navigator={this.props.navigator}
navigationBar={
<Navigator.NavigationBar style={{backgroundColor: 'transparent'}}
routeMapper={NavigationBarRouteMapper} />
} />
);
}
renderScene() {
return (
<View style={styles.credentialContainer}>
<View style={styles.inputContainer}>
<Icon style={styles.inputPassword} name="person" size={28} color="#FFCD00" />
<View style={{flexDirection: 'row', flex: 1, marginLeft: 2, marginRight: 2, borderBottomColor: '#e0e0e0', borderBottomWidth: 2}}>
<TextInput
ref = "FirstInput"
style={styles.input}
placeholder="Username"
autoCorrect={false}
autoCapitalize="none"
returnKeyType="next"
placeholderTextColor="#e0e0e0"
onChangeText={(text) => this.setState({username: text})}
value={this.state.username}
onSubmitEditing={(event) => {
this.refs.SecondInput.focus();
}}
>
</TextInput>
</View>
</View>
<View style={styles.inputContainer}>
<Icon style={styles.inputPassword} name="lock" size={28} color="#FFCD00" />
<View style={{flexDirection: 'row', flex: 1, marginLeft: 2, marginRight: 2, borderBottomColor: '#e0e0e0', borderBottomWidth: 2}}>
<TextInput
ref = "SecondInput"
style={styles.input}
placeholder="Password"
autoCorrect={false}
secureTextEntry={true}
placeholderTextColor="#e0e0e0"
onChangeText={(text) => this.setState({password: text})}
value={this.state.password}
returnKeyType="done"
onSubmitEditing={(event)=> {
this.login();
}}
focus={this.state.focusPassword}
>
</TextInput>
</View>
</View>
</View>
);
}
Try setting the reference using a function. Like this:
<TextInput ref={(ref) => { this.FirstInput = ref; }} />
Then you can access to the reference with this.FirstInput instead of this.refs.FirstInput
For a functional component using the useRef hook. You can use achieve this easily, with...
import React, { useRef } from 'react';
import { TextInput, } from 'react-native';
function MyTextInput(){
const textInputRef = useRef<TextInput>(null);;
return (
<TextInput ref={textInputRef} />
)
}
Try changing the Navigator's renderScene callback to the following (based on Navigator documentation) cause you will need the navigator object later.
renderScene={(route, navigator) => this.renderScene(route, navigator)}
Then, use 'navigator' instead of 'this' to get the refs.
navigator.refs.SecondInput.focus()

Image preloading in React Native

I am building my first app with React Native, an app with a long list of images. I want to show a spinner instead of image while image is loading. It is sounds trivial but i didn't found a solution.
I think for a spinner i suppose to use ActivityIndicatorIOS , but how am i combining it with an Image component?
<Image source={...}>
<ActivityIndicatorIOS />
</Image>
Is this a right direction? Am i missing something?
I will share my solution
<View>
<Image source={{uri: this.state.avatar}} style={styles.maybeRenderImage}
resizeMode={"contain"} onLoadStart={() => this.setState({loading: true})}
onLoadEnd={() => {
this.setState({loading: false})
}}/>
{this.state.loading && <LoadingView/>}
</View>
LoadingView.js
export default class LoadingView extends Component {
render() {
return (
<View style={styles.container}>
<ActivityIndicator size="small" color="#FFD700"/>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
position: "absolute",
left: 0,
right: 0,
top: 0,
bottom: 0,
opacity: 0.7,
backgroundColor: "black",
justifyContent: "center",
alignItems: "center",
}
});
Here is a complete solution to providing a custom image component with a loading activity indicator centered underneath the image:
import React, { Component } from 'react';
import { StyleSheet, View, Image, ActivityIndicator } from 'react-native';
export default class LoadableImage extends Component {
state = {
loading: true
}
render() {
const { url } = this.props
return (
<View style={styles.container}>
<Image
onLoadEnd={this._onLoadEnd}
source={{ uri: url }}
/>
<ActivityIndicator
style={styles.activityIndicator}
animating={this.state.loading}
/>
</View>
)
}
_onLoadEnd = () => {
this.setState({
loading: false
})
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
},
activityIndicator: {
position: 'absolute',
left: 0,
right: 0,
top: 0,
bottom: 0,
}
})
I will share my own solution based only on CSS manipulation, which in my opinion is easy to understand, and the code is pretty clean. The solution is a little similar to other answers, but doesn't require absolute position of any component, or creating any additional components.
The idea is to switch between showing an <Image> and <ActivityIndicator>, based on some state variable (isImageLoaded in the snippet below).
<View>
<Image source={...}
onLoad={ () => this.setState({ isImageLoaded: true }) }
style={[styles.image, { display: (this.state.isImageLoaded ? 'flex' : 'none') }]}
/>
<ActivityIndicator
style={{ display: (this.state.isImageLoaded ? 'none' : 'flex') }}
/>
</View>
Also you should set image size using flex property (otherwise image will be invisible):
const styles = StyleSheet.create({
image: {
flex: 1,
}
});
Note that you don't have to initiate the isImageLoaded variable to false in the constructor, because it will have undefined value and the if conditions will act as expected.
Just ran into the same issue. So basically you have the correct approach, but the indicator should of course only be rendered when the image is loading. To keep track of that you need state. To keep it simple we assume you have just on image in the component an keep the state for it in the same component. (The cool kids will argue you should use a higher order component for that and then pass the state in via a prop ;)
The idea then is, that your image starts out loading and onLoadEnd (or onLoad, but then the spinner gets stuck on error, which is fine or course) you re-set the state.
getInitialState: function(){ return { loading: true }}
render: function(){
<Image source={...} onLoadEnd={ ()=>{ this.setState({ loading: false }) }>
<ActivityIndicatorIOS animating={ this.state.loading }/>
</Image>
}
You could also start out with { loading: false } and set it true onLoadStart, but I'm not sure what the benefit would be of that.
Also for styling reasons, depending on your layout, you might need to put the indicator in a container view that is absolutely positioned. But you get the idea.
Yes, deafultSource and loadingIndicatorSource is not working properly. Also image component cannot contain children. Try this solutions => https://stackoverflow.com/a/62510268/11302100
You can simply just add a placeholder
import { Image } from 'react-native-elements';
<Image
style={styles(colors).thumbnail}
source={{ uri: event.image }}
PlaceholderContent={<ActivityIndicator color={colors.indicator} />}
/>
const [imageLoading, setIsImageLoading] = useState(true);
<View>
<View
style={[
{justifyContent: 'center', alignItems: 'center'},
imageLoading ? {display: 'flex'} : {display: 'none'},
]}>
<ActivityIndicator />
</View>
<Image
source={{uri: ""}}
onLoadEnd={() => {setIsImageLoading(false)}}
style={[
imageStyle,
imageLoading ? {display: 'none'} : {display: 'flex'},
]}
/>
</View>

Resources