I have written a program in which I am showing a list of images in ScrollView when user clicks an image a modal is popped up and image would be shown in large size. But this is not working.
Modal is opening fine but it is not showing the image..
However I have checked the value of image in render method of Modal i.e. ImageViewer, value I am getting is a class object.
App:
import React, {Component} from 'react';
import {View,Modal, ScrollView, Image, TouchableOpacity, StyleSheet} from 'react-native';
import pic1 from './images/sl13.png';
import pic2 from './images/sl14.png';
import pic3 from './images/sl15.png';
import pic4 from './images/sl16.png';
import pic5 from './images/sl17.png';
class App extends Component {
Images = [pic1, pic2, pic3, pic4, pic5];
state = {
modalVisible: false,
}
image = null
close(){
this.setState({modalVisible: false});
}
constructor(props){
super(props);
this.close = this.close.bind(this);
}
showImage(path){
this.image = path;
this.setState({modalVisible: true});
}
render() {
return (
<View style={{alignItems:'center', justifyContent: 'center'}}>
<ScrollView>
{this.Images.map((item)=>{
return (
<TouchableOpacity key={item} onPress={(item)=>this.showImage(item)}>
<View style={{borderColor: 'red', borderWidth: 1, marginBottom: 10}}>
<Image style={{width: 200, height: 200}} source={item} />
</View>
</TouchableOpacity>
)
})}
</ScrollView>
<ImageViewer closeModal={()=>this.close()} modalVisible={this.state.modalVisible} image={this.image}/>
</View>
);
}
}
Modal:
class ImageViewer extends Component {
render() {
console.log(this.props.image) //Checking Value here
return (
<Modal
style={{top: '50%', left: '50%', transform: 'translate(-50%, -50%) !important'}}
animationType='fade'
transparent={true}
onRequestClose={()=>this.props.closeModal()}
visible={this.props.modalVisible}
>
<View style={{flex:1 ,alignItems: 'center', justifyContent: 'center', backgroundColor:'#00000069'}}>
<View style={{padding:20 , backgroundColor:'#fff', borderRadius: 10}}>
<Image style={{width: 400, height: 600}} source={this.props.image} />
</View>
</View>
</Modal>
)
}
}
export default App;
both are in same file..
Screenshots :
Normal : https://imgur.com/deai02Y.jpg
Clicked on Image: https://imgur.com/POuZlPU.jpg
On Touchableopacity onPress you are actually passing the onPress $event to showImage function instead of item. so correct way of doing it is
<View style={{alignItems:'center', justifyContent: 'center'}}>
<ScrollView>
{this.Images.map((item)=>{
return (
<TouchableOpacity key={item} onPress={()=>this.showImage(item)}>
<View style={{borderColor: 'red', borderWidth: 1, marginBottom: 10}}>
<Image style={{width: 200, height: 200}} source={item} />
</View>
</TouchableOpacity>
)
})}
</ScrollView>
<ImageViewer closeModal={()=>this.close()} modalVisible={this.state.modalVisible} image={this.image}/>
</View>
after app called write
constructor(props) {
super(props);
this.state = {
image : ''
};
}
and in showImage path
showImage(path){
this.setstate({image : path});
this.setState({modalVisible: true});
}
and in Imageviewer
<ImageViewer closeModal={()=>this.close()} modalVisible={this.state.modalVisible} image={this.state.image}/>
Related
I am using react native. Now, when I try to center the flatlist in the center of the screen with either specifically giving the flatlist with justifyContent and alignItems, it gives me a weird action. Also, contentContainerStyle with justifyContent and alignItems as center also gives an weird action. Been searching all day yestarday for solution. I will provide code and image below. Thank you.
im trying to align this flatlist in the center just like justfyContent and alignItems would do. You can see that the content leans towards the left of the screen.
import React, { useState } from "react";
import { View, Text , Button, FlatList, ActivityIndicator, TouchableOpacity } from "react-native";
import { GlobalStyles } from "../styles/GlobalStyles";
import PokeDetails from "./PokeDetails";
import SearchBarComponent from "../components/SearchBar";
import PokeBanner from "../components/PokeBanner";
class Home extends React.Component {
constructor(props) {
super(props);
this.state = {
isLoading: true,
dataSource: [],
}
}
componentDidMount() {
fetch(`https://pokeapi.co/api/v2/pokemon/?limit=27`)
.then((res)=> res.json())
.then((response)=> {
this.setState({
isLoading: false,
dataSource: response.results,
})
console.log("RESPONSE",response)
console.log("RESPONSE.RESSSULTS",response.results)
})
}
render() {
const showIndicator = this.state.isLoading == true ? <ActivityIndicator size="large" color="#0000ff" /> : null;
return(
<View style={GlobalStyles.container}>
<SearchBarComponent style={GlobalStyles.searchBar}/>
<PokeBanner/>
<View style={GlobalStyles.activityIndicator}>{showIndicator}</View>
<View style={GlobalStyles.pokeFlatList}>
<FlatList
contentContainerStyle={{flexDirection: "row",justifyContent:"center", alignItems:"center"}}
keyExtractor={(item, index) => item.name}
numColumns={3}
data={this.state.dataSource}
renderItem={({item})=>
<View style={{flex: 1, flexDirection: "column", margin: 1}}>
<TouchableOpacity onPress={()=> this.props.navigation.navigate('PokeDetails',
{item ,imageUrl: `https://projectpokemon.org/images/normal-sprite/${item.name}.gif`})}>
<PokeDetails imageUrl={`https://projectpokemon.org/images/normal-sprite/${item.name}.gif`} name={item.name}/>
</TouchableOpacity>
</View>
}/>
</View>
<Button onPress={()=> this.props.navigation.navigate("About")} title="Go to about"/>
</View>
)
}
}
export default Home;
This is what happens when I try to add contentContainerStyle using the code below
import React, { useState } from "react";
import { View, Text , Button, FlatList, ActivityIndicator, TouchableOpacity } from "react-native";
import { GlobalStyles } from "../styles/GlobalStyles";
import PokeDetails from "./PokeDetails";
import SearchBarComponent from "../components/SearchBar";
import PokeBanner from "../components/PokeBanner";
class Home extends React.Component {
constructor(props) {
super(props);
this.state = {
isLoading: true,
dataSource: [],
}
}
componentDidMount() {
fetch(`https://pokeapi.co/api/v2/pokemon/?limit=27`)
.then((res)=> res.json())
.then((response)=> {
this.setState({
isLoading: false,
dataSource: response.results,
})
console.log("RESPONSE",response)
console.log("RESPONSE.RESSSULTS",response.results)
})
}
render() {
const showIndicator = this.state.isLoading == true ? <ActivityIndicator size="large" color="#0000ff" /> : null;
return(
<View style={GlobalStyles.container}>
<SearchBarComponent style={GlobalStyles.searchBar}/>
<PokeBanner/>
<View style={GlobalStyles.activityIndicator}>{showIndicator}</View>
<View style={GlobalStyles.pokeFlatList}>
<FlatList
contentContainerStyle={{justifyContent:"center", alignItems:"center"}}
keyExtractor={(item, index) => item.name}
numColumns={3}
data={this.state.dataSource}
renderItem={({item})=>
<View style={{flex: 1, flexDirection: "column", margin: 1}}>
<TouchableOpacity onPress={()=> this.props.navigation.navigate('PokeDetails',
{item ,imageUrl: `https://projectpokemon.org/images/normal-sprite/${item.name}.gif`})}>
<PokeDetails imageUrl={`https://projectpokemon.org/images/normal-sprite/${item.name}.gif`} name={item.name}/>
</TouchableOpacity>
</View>
}/>
</View>
<Button onPress={()=> this.props.navigation.navigate("About")} title="Go to about"/>
</View>
)
}
}
export default Home;
For this you can use FlatList columnWrapperStyle and remove flex:1 from your View
change:
<FlatList
contentContainerStyle={{justifyContent:"center", alignItems:"center"}}
keyExtractor={(item, index) => item.name}
numColumns={3}
data={this.state.dataSource}
renderItem={({item})=>
<View style={{flex: 1, flexDirection: "column", margin: 1}}>
<TouchableOpacity onPress={()=> this.props.navigation.navigate('PokeDetails',
{item ,imageUrl: `https://projectpokemon.org/images/normal-sprite/${item.name}.gif`})}>
<PokeDetails imageUrl={`https://projectpokemon.org/images/normal-sprite/${item.name}.gif`} name={item.name}/>
</TouchableOpacity>
</View>
}/>
to
<FlatList
columnWrapperStyle={{ flex: 1,justifyContent: "space-around"}}
keyExtractor={(item, index) => item.name}
numColumns={3}
data={this.state.dataSource}
renderItem={({item})=>
<View style={{ flexDirection: "column", margin: 1}}>
<TouchableOpacity onPress={()=> this.props.navigation.navigate('PokeDetails',
{item ,imageUrl: `https://projectpokemon.org/images/normal-sprite/${item.name}.gif`})}>
<PokeDetails imageUrl={`https://projectpokemon.org/images/normal-sprite/${item.name}.gif`} name={item.name}/>
</TouchableOpacity>
</View>
}/>
Hope this helps!
The only thing you have to do is change the style of renderItem of FlatList from,
<View style={{flex: 1, flexDirection: "column", margin: 1}}>
to
<View style={{ flex: 1, justifyContent: 'center', alignItems: 'center', margin: 1 }}>
also remove your contentContainerStyle from FlatList.
For more information check below working example (remove some code to make a minimum working example)
import React from "react";
import { View, FlatList, Image, Text } from "react-native";
export default class Home extends React.Component {
state = {
isLoading: true,
dataSource: [],
};
componentDidMount() {
fetch(`https://pokeapi.co/api/v2/pokemon/?limit=27`)
.then((res) => res.json())
.then((response) => {
this.setState({
isLoading: false,
dataSource: response.results,
});
});
}
render() {
return (
<View>
<FlatList
data={this.state.dataSource}
keyExtractor={(item) => item.name}
numColumns={3}
renderItem={({ item }) =>
<View style={{flex: 1, justifyContent: "center", alignItems: "center", margin: 1}}>
<Image
source={{uri: `https://projectpokemon.org/images/normal-sprite/${item.name}.gif`}}
style={{ width: 75, height: 75 }}
/>
<Text>{item.name}</Text>
</View>
}
/>
</View>
);
}
}
Hope this helps you. Feel free for doubts.
I made a webview application with react native to display the Facebook website but there was a problem when I wanted to upload a photo by clicking the upload photo button in the pop status section there was no response ... what was the solution?
import React, { Component } from 'react';
import { Button, View, WebView, StyleSheet, TouchableOpacity, Text, Image } from 'react-native';
export default class App extends Component {
constructor(props) {
super(props);
this.reload = this.reload.bind(this);
}
reload() {
this.webview.reload();
}
render() {
return (
<View style={{ flex: 1 }}>
<View style={{ height: 20 }} />
<WebView
ref={ref => (this.webview = ref)}
source={{ uri: 'https://facebo.com' }}
onError={console.error.bind(console, 'error')}
bounces={false}
onShouldStartLoadWithRequest={() => true}
javaScriptEnabledAndroid={true}
startInLoadingState={true}
style={{ flex: 1 }}
/>
<View style={{alignItems:'center'}}>
<TouchableOpacity onPress={this.reload}>
<Image source={require('../assets/reload.png')} style={styles.fab} />
</TouchableOpacity>
</View>
</View>
);
}
}
const styles = StyleSheet.create({
fab: {
width: 40,
height: 40,
justifyContent: 'center',
},
});
I tried several codes but I only have errors every time.
How to add images from my gallery (no links) one below the other, with text
at the top and bottom of each image?
Like this:
(source: noelshack.com)
import React, { Component } from "react";
import { Text, View, StyleSheet, Image, ImageBackground,ScrollView } from "react-native";
import withBackground from "../components/WithBackground";
class LinksScreen extends Component {
render() {
return (
<ScrollView>
<text>Hi</text>
<Image source={require('./assets/images/ici.jpg')} />
<text> Hello</text>
<text> Hi2</text>
<Image source={require('./assets/images/ici2.jpg')} />
<text> Hello2</text>
</ScrollView>
);
}}
export default withBackground(LinksScreen);
I am novice,
any help would be appreciated.
Can you give a screenshot of the result you are expecting?
There is something called a FlatList you can use that to achieve a list of images.
Note : menuData is an array of objects and Item is an object that has image title and URL
<FlatList
data={this.props.menuData}
renderItem={({ item }) => {
return(
<View style={{ flexDirection: 'row' }}>
<Image source={require(item.imageURL)} />
<Text>{item.imageText}</Text>
</View>
);
}}
keyExtractor={(item) => item.title }
/>
Use this style for Text:
textStyle: {
flex: 1,
width: '100%',
position: 'absolute',
alignSelf: 'center',
backgroundColor: 'rgba(0.57, 0.57, 0.57, 0.3)',
height: '100%',
}
I am going to show you a possibility of working with native-base, but it's just a suggestion. You can see some possibilities in the official docs: https://docs.nativebase.io/Components.html#Components
import React, { Component } from 'react';
import { Image, ImageBackground, View } from 'react-native';
import { Card, CardItem, Text, Left, Right } from 'native-base';
import styles from './styles';
class ProductImage extends Component {
render() {
return (
<View style={{ flex: 1 }}>
<ImageBackground
style={ styles.image }
source={{ uri: this.props.photo }}
>
</ImageBackground>
</View>
);
}
}
export default ProductImage
So if you want to put a photo without props, it's just put the link image, like 'https://www.w3schools.com/w3css/img_lights.jpg'. Don't forget to install the dependence: npm install native-base --save
Can you try this once:
<ScrollView>
<View>
<Text>Hi</Text>
<Image source={require('./assets/snack-icon.png')} style={{ width: '100%',
height: 150, marginBottom: 10, padding: 10 }} resizeMode="cover" />
</View>
<View>
<Text> Hi2</Text>
<Image source={require('./assets/snack-icon.png')} style={{ width: '100%',
height: 150, marginBottom: 10, padding: 10 }} resizeMode="cover" />
<Text> Hello2</Text>
</View>
</ScrollView>
I'm having trouble learning how to pass data between parent and child in React Native.
In my parent component I have a state property (audioPlaying) which is a Boolean value.
state = {
//The title informs the Button and TitleArea components
title: 'hello',
audioPlaying: false,
};
I'd like to change that value on the press of a button (onPress).
<Button
title={this.state.title}
onPress={this.playPauseHandler}
audioPlaying={this.state.audioPlaying}
/>
...by calling the playPauseHandler.
playPauseHandler = () => {
this.setState(prevState => ({
audioPlaying: !prevState.audioPlaying
}));
}
Then in my child (Button) Component I want to evaluate the audioPlaying state property. If it's true, I want to show one things and false I want to show something else.
<View style={styles.playBtnStyle}>
{this.props.audioPlaying === false ? (
<MaterialIcons
name='play-arrow'
size={50}
color="#87888C"
/>
) : (
<MaterialIcons
name='pause'
size={50}
color="#87888C"
/>
)}
}
</View>
However, when I run this I get undefined for the value of audioPlaying.
React Native Error Message
Here are the full files for both:
App.js
import React, { Component } from 'react';
import { View, StatusBar } from 'react-native';
import Carousel from './src/components/Carousel/Carousel';
import Button from './src/components/Button/Button';
import TitleArea from './src/components/TitleArea/TitleArea';
import MapArea from './src/components/MapArea/MapArea';
const styles = {
container: {
flex: 1,
justifyContent: 'space-between',
},
playArea: {
flex: 1,
},
};
export default class App extends Component {
state = {
//The title informs the Button and TitleArea components
title: 'hello',
audioPlaying: false,
};
playPauseHandler = () => {
this.setState(prevState => ({
audioPlaying: !prevState.audioPlaying
}));
}
render() {
return (
<View style={styles.container}>
<TitleArea title={this.state.title} />
<StatusBar hidden={false} />
<Carousel />
<MapArea />
<Button
title={this.state.title}
onPress={this.playPauseHandler}
audioPlaying={this.state.audioPlaying}
/>
</View>
);
}
}
Button.js
import React, { Component } from 'react';
import { Text, View, TouchableOpacity, Dimensions } from 'react-native';
import MaterialIcons from 'react-native-vector-icons/MaterialIcons';
const { width } = Dimensions.get('window');
const height = width * 0.2;
const styles = {
textStyle: {
color: '#87888C',
fontSize: 18,
fontWeight: '600',
backgroundColor: 'white',
alignSelf: 'center',
},
buttonContainer: {
height,
flexDirection: 'row',
backgroundColor: 'white',
alignItems: 'center',
},
playBtnStyle: {
marginLeft: 50,
backgroundColor: 'white',
},
childStyle: {
flex: 1,
},
};
const button = (props) => {
return (
<View style={styles.buttonContainer}>
<TouchableOpacity>
<View style={styles.playBtnStyle}>
{this.props.audioPlaying === false ? (
<MaterialIcons
name='play-arrow'
size={50}
color="#87888C"
/>
) : (
<MaterialIcons
name='pause'
size={50}
color="#87888C"
/>
)}
}
</View>
</TouchableOpacity>
<View style={styles.childStyle}>
<Text style={styles.textStyle}>Chapter 1: {props.title}</Text>
</View>
</View>
);
}
export default button;
There is no this in the context of button. That is just a function returning JSX.
Instead, use props
<View style={styles.playBtnStyle}>
{props.audioPlaying === false ? (
<MaterialIcons
name='play-arrow'
size={50}
color="#87888C"
/>
) : (
<MaterialIcons
name='pause'
size={50}
color="#87888C"
/>
)}
</View>
Ok so I solved my own problem! (step one to being a developer)
Two issues:
Capturing Touch Events
React Native has what's called Touchables. According to the documentation these are "wrappers that make views respond properly to touches".
TouchableOpacity, the one I'm using:
On press down, the opacity of the wrapped view is decreased, dimming it. Opacity is controlled by wrapping the children in an Animated.View, which is added to the view hierarchy.
https://facebook.github.io/react-native/docs/touchablewithoutfeedback#onpress
All Touchables accept the onPress prop. So by adding the onPress prop to the Touchable, I'm able to capture the touch event instead of just firing it.
Passing Callback to Parent
This article helped me understand more about how a parent function can be called from a child.
https://medium.com/#thejasonfile/callback-functions-in-react-e822ebede766
So I'm calling playPause() (I renamed the prop and destructured it) in TouchableOpacity, which fires from a touch event causing state to change and component to re-render.
const button = (props) => {
const {
title,
audioPlaying,
playPause,
} = props;
return (
<View style={styles.buttonContainer}>
<TouchableOpacity onPress={() => playPause()}>
<View style={styles.playBtnStyle}>
{audioPlaying === false ? (
<MaterialIcons
name='play-arrow'
size={50}
color="#87888C"
/>
) : (
<MaterialIcons
name='pause'
size={50}
color="#87888C"
/>
)
}
</View>
</TouchableOpacity>
<View style={styles.childStyle}>
<Text style={styles.textStyle}>
Chapter 1:
{title}
</Text>
</View>
</View>
);
};
As per title, I would like to have a modal opened when clicked on a view
app.js
<View>
<MediaBar onClick={this.toggleModal}> />
<Modal show={this.state.isOpen}
onClose={this.toggleModal}>
`Here's some content for the modal`
</Modal>
</View>
Mediabar.js: https://pastebin.com/6bW5gz99
modal.js: https://pastebin.com/3vQgLyTg
The Modal component has a visible property.
https://facebook.github.io/react-native/docs/modal.html
You just have to update its value using your parent component state.
I will do something like this
App.js
import React, { Component } from 'react';
import { View, Text, Modal, TouchableWithoutFeedback, Dimensions, TouchableOpacity } from 'react-native';
class App extends Component {
state = {
modalVisible: false
}
render() {
return(
<View style={this.styles.viewStyle}>
<Modal visible={this.state.modalVisible}
transparent={true}>
<View style={this.styles.viewStyle}>
<View style={this.styles.dialogStyle}>
</View>
</View>
</Modal>
<View style={this.styles.anotherView}>
<TouchableOpacity onPress={()=> this.setState({ modalVisible: true})}>
<Text>Hello</Text>
</TouchableOpacity>
</View>
</View>
);
}
styles = {
viewStyle: {
flex:1,
alignItems: 'center',
justifyContent: 'center'
},
dialogStyle: {
height: Dimensions.get('window').height*0.2,
width: Dimensions.get('window').width*0.9,
backgroundColor: '#d3d3d3',
elevation: 10,
borderRadius: 5
},
anotherView:{
flex: 1,
backgroundColor: 'white',
alignItems: 'center',
justifyContent: 'center'
}
}
}
export default App;
To Achieve the modal like below: