ReactNative TouchableOpacity makes view dissapear? - javascript

Consider the following example:
import * as React from 'react';
import { Text, View, StyleSheet, Image, TouchableOpacity} from 'react-native';
import snackicon from './assets/snack-icon.png';
export default function App() {
return (
<>
{/*<TouchableOpacity onPress={() => console.log("View clicked")}>*/}
<View style={{flex: 1, flexDirection: 'row', backgroundColor: '#00000050', marginRight: 5, borderRadius: 15}}>
<View style={{flex: 1}}>
<Image style={{alignSelf: 'stretch', flex: 1, resizeMode: 'contain', width: 'auto' }} source={snackicon}></Image>
</View>
<View style={{flex: 3}}>
</View>
</View>
{/*</TouchableOpacity>*/}
<View style={{flex: 10, flexDirection: 'column'}}></View>
</>
);
}
This shows a view with an Image in it; However if you uncomment the TouchableOpacity the entire view disappears. What exactly is causing this?
Expo link if anyone wants to try live: https://snack.expo.io/qt_gAkTaM

You are using flex: 1 to define the height of your nested View component. Since it has a flex: 1 and your other View has flex: 10, it takes 1/10 of the screen.
Your TouchableOpacity doesn't have a height nor flex property, so it doesn't grow.
I suggest trying to put flex: 1 in the styles of TouchableOpacity.

Related

React Native - add a masked circle overlay over image

How do I go about adding an opaque circular overlay over an image in React Native? Similar to the instagram image picker:
as trivial a task this may seem, I've had a world of trouble replicating this. Any suggestions?
As someone mentioned in the comments, the way to achieve this is with React Native Masked View.
Install it in your project by running:
npm install -S #react-native-community/masked-view
or
yarn add #react-native-community/masked-view
Then you can use it as follows. I've adapted the example from their README for you here:
import MaskedView from '#react-native-community/masked-view';
import React from 'react';
import { View } from 'react-native';
export default class App extends React.Component {
render() {
return (
<View
style={{
flex: 1,
backgroundColor: '#000000', // "Edge" background
maxHeight: 400,
}}
>
<MaskedView
style={{ flex: 1 }}
maskElement={
<View
style={{
// Transparent background mask
backgroundColor: '#00000077', // The '77' here sets the alpha
flex: 1,
}}
>
<View
style={{
// Solid background as the aperture of the lens-eye.
backgroundColor: '#ff00ff',
// If you have a set height or width, set this to half
borderRadius: 200,
flex: 1,
}}
/>
</View>
}
>
{/* Shows behind the mask, you can put anything here, such as an image */}
<View style={{ flex: 1, height: '100%', backgroundColor: '#324376' }} />
<View style={{ flex: 1, height: '100%', backgroundColor: '#F5DD90' }} />
<View style={{ flex: 1, height: '100%', backgroundColor: '#F76C5E' }} />
<View style={{ flex: 1, height: '100%', backgroundColor: '#2E6D3E' }} />
</MaskedView>
</View>
);
}
}
import React from 'react';
import {
SafeAreaView,
StyleSheet,
View,
Image,
Text
} from 'react-native';
const Test = () => {
return (
<SafeAreaView style={{flex: 1}}>
<View style={styles.container}>
<Image
source={{
uri: 'https://raw.githubusercontent.com/AboutReact/sampleresource/master/old_logo.png'
}}
//borderRadius will help to make Round Shape
style={{
width: 200,
height: 200,
borderRadius: 200 / 2
}}
/>
<Text style={styles.textHeadingStyle}>
About React
</Text>
</View>
</SafeAreaView>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#e0dcdc',
},
textHeadingStyle: {
marginTop: 30,
fontSize: 40,
color: '#0250a3',
fontWeight: 'bold',
},
});
export default Test;
import React, { Component } from 'react';
import {
View,
StyleSheet,
Text,
ScrollView,
TouchableOpacity,
} from 'react-native';
import styles from './styles';
import { Circle, CustomHeader, CustomImage, CTNexaBold } from '../../components';
import translate from '../../translations/translate';
import { images, icons } from '../../assets'
import { widthPercentageToDP as wp, heightPercentageToDP as hp } from 'react-native-responsive-screen';
import utils from '../../utils';
import { Colors } from '../../common';
import ImagePicker from 'react-native-image-crop-picker';
class UploadProfilePicture extends Component {
constructor(props) {
super(props);
this.state = {
profileImage: '',
isProfileImage: false,
};
}
componentDidMount() {
};
changeProfilePhoto() {
ImagePicker.openPicker({
width: 300,
height: 400,
cropping: true
}).then(image => {
this.setState({
profileImage: image.path,
isProfileImage: true,
})
});
}
render() {
const { profileImage, isProfileImage } = this.state
return (
<View style={styles.container}>
{utils.statusBar('dark-content', Colors.white)}
<CustomHeader
title={<CTNexaBold customStyle={styles.customStyle} >{translate("Upload Profile Picture")}</CTNexaBold>}
{...this.props}
/>
<View style={{ flex: 0.8, alignItems: 'center', justifyContent: 'center', marginBottom: 200 }} >
<View>
<Circle
width={wp('44%')}
height={wp('44%')}
borderRadius={wp('44%')}
borderColor={'#A28A3D'}
marginVertical={40}
marginHorizontal={70}
>
<CustomImage
style={styles.userAvatar}
// source={images.iconProfile}
source={ isProfileImage ? { uri: profileImage } : images.iconProfile }
/>
</Circle>
</View>
<View style={{ marginHorizontal: wp('10%') }} >
<TouchableOpacity onPress={()=>this.changeProfilePhoto()} >
<View style={{ flexDirection: 'row', justifyContent: 'space-between' }} >
<CTNexaBold customStyle={styles.profileText} >Change Profile Photo</CTNexaBold>
<CustomImage
style={styles.containerCustomImage}
source={icons.arrowRight}
/>
</View>
</TouchableOpacity>
</View>
</View>
<View style={{ flex: 0.2, alignItems: 'center', justifyContent: 'center', marginBottom: 20 }} >
<TouchableOpacity style={styles.saveButton} >
<CTNexaBold customStyle={styles.saveButtonText} >SAVE</CTNexaBold>
</TouchableOpacity>
</View>
</View>
);
}
}
export default UploadProfilePicture;

React Native: How does this Component call?

Can someone help me with this Component, i want to make like this, but dont know how this white frames called? Can someone tell me this? And if we press that yellow Touchable Opacity it is showing whole Text, and if we press again it will became smaller!
Thanks in Advance , I am Just new in RN
You can easily create that card with a little bit of CSS.
Below is the sample app which shows you how you can achieve that.
Working Example: Expo Snack
import React, { useState, useEffect } from 'react';
import {
Text,
View,
StyleSheet,
FlatList,
Image,
TouchableOpacity,
} from 'react-native';
import { AntDesign } from '#expo/vector-icons';
import Constants from 'expo-constants';
import { newsFeed } from './news';
export default function App() {
const [news, setNews] = useState(newsFeed);
const showFull = (index) => {
const temp = [...news];
temp[index].toggle = !temp[index].toggle;
setNews(temp);
};
return (
<View style={styles.container}>
<FlatList
data={news}
renderItem={({ item, index }) => (
<View style={styles.card}>
<Text style={styles.title}>{item.title}</Text>
<Text style={styles.paragraph}>
{item.toggle ? item.desc : `${item.desc.substr(0, 100)}...`}
</Text>
{item.toggle && (
<Image source={{ uri: item.img }} style={styles.img} />
)}
<View style={styles.bottomBar}>
<Text style={styles.date}>4/02/2021</Text>
<TouchableOpacity onPress={() => showFull(index)}>
<View style={{ flexDirection: 'row', alignItems: 'center' }}>
<Text style={styles.moreBtn}>
{!item.toggle ? 'More' : 'Less'}
</Text>
<AntDesign
name={item.toggle ? 'up' : 'down'}
size={12}
color="orange"
/>
</View>
</TouchableOpacity>
</View>
</View>
)}
/>
</View>
);
}
const styles = StyleSheet.create({
bottomBar: {
marginVertical: 5,
flexDirection: 'row',
justifyContent: 'space-between',
},
container: {
flex: 1,
justifyContent: 'center',
paddingTop: Constants.statusBarHeight,
backgroundColor: '#ecf0f1',
padding: 8,
},
card: {
padding: 10,
backgroundColor: 'white',
marginVertical: 5,
borderRadius: 10,
},
title: {
marginVertical: 5,
fontSize: 18,
fontWeight: 'bold',
},
img: {
flex: 1,
height: 100,
borderRadius: 10,
marginVertical: 5,
},
paragraph: {
fontSize: 14,
},
date: {
fontSize: 12,
color: 'rgba(21,21,21,0.5)',
},
moreBtn: {
fontSize: 12,
color: 'orange',
marginRight: 10,
},
});
actually this card is not a component you can design it using css and if you want to create a component which you can reuse then you can make one component and reuse it as you want and for this card either you can use your own css or a library called native-base which is
like bootstrap but it is used in react-native
you can read about native base here for more information
https://nativebase.io/
and if you want to create card of your own then make a separate file and make a funcional card component in it
and call it wherever you like
import myCustomCard from './card'
and to use it you use like this in your jsx
<myCustomCard />
and if you want to know more about how to pass props and else you can checkout official docs of the react native here
https://reactnative.dev/docs/getting-started

TextBox above Keyboard

I am new to React Native and I have encountered a problem: my TextBox doesn't stay above the keyboard while I am writing in it.
These are the visuals from the application
Screenshot
And this is my Signup.js:
import React, { Component } from 'react';
import {
StyleSheet,
Text,
View,
TouchableOpacity
} from 'react-native';
import Form from '../components/Form';
import Logo2 from'../components/Logo2';
import {Actions} from 'react-native-router-flux';
export default class Signup extends Component {
goBack() {
Actions.pop()
}
render() {
return(
<View style={styles.container}>
<Logo2/>
<Form type="Registrar"/>
<View style={styles.signupTextCont}>
<Text style={styles.signupText}>Ja tens uma conta? </Text>
<TouchableOpacity onPress={this.goBack}><Text style={styles.signupButton}>Entra</Text></TouchableOpacity>
</View>
</View>
)
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#232122'
},
signupTextCont: {
flexGrow: 1,
justifyContent: 'center',
alignItems: 'flex-end',
paddingVertical: 16,
flexDirection: 'row'
},
signupText: {
color: 'rgba(255,255,255,0.7)',
fontSize:16
},
signupButton: {
color: '#FFA200',
fontSize:16,
fontWeight: '500'
}
});
I don't know what I need to code.
Could you please help me?
To replicate my comment that resolved your problem; you can use the component KeyboardAvoidingView from the package react-native. It levels up the area it contains above your virtual keyboard.
Wrap your code like this:
<KeyboardAvoidingView behavior={'position'} enabled>
<View style={styles.signupTextCont}>
<Text style={styles.signupText}>Ja tens uma conta? </Text>
<TouchableOpacity onPress={this.goBack}>
<Text style={styles.signupButton}>Entra</Text>
</TouchableOpacity>
</View>
</KeyboardAvoidingView>
Here's some more info about how it works: https://facebook.github.io/react-native/docs/keyboardavoidingview.
You can wrap your code with KeyboardAvoidingView rather than a normal View so that it can actually lift up any items inside it above the keyboard. You can use <KeyboardAvoidingView behavior="padding">
Hope it helps.

How to add images? (React Native)

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>

positioning react elements

The following code works but wondering if this is really the best way to accomplish the task at hand. Two TextInput fields, when show = true display both of them. When show = false display the first one in the same position on the screen and not display the second one. We've substituted a blank Text element to take up the space of the second TextInput element. Is that the right way to do this? It seems a little hokey.
import React from 'react';
import { StyleSheet, TextInput, View, Button, Text } from 'react-native';
export default class App extends React.Component {
state={show: true,}
handleElement(){}
handleKey(){}
onSubmit=()=>{
this.setState({show:!this.state.show})
// this.setState(prevState =>({show:!prevState.show}))
}
render() {
return (
<View style={styles.container}>
{ this.state.show &&
<View>
<TextInput style={styles.input}
placeholder='Element'
onChangeText={this.handleElement} />
<TextInput style={styles.input}
placeholder='Key'
onChangeText={this.handleKey}/>
<Button title='Add' onPress={this.onSubmit} />
</View>
}
{ !this.state.show &&
<View>
<TextInput style={styles.input}
placeholder='Element'
onChangeText={this.handleElement} />
<Text style={styles.blank}> </Text>
<Button title='Add' onPress={this.onSubmit} />
</View>
}
</View>
)
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
},
input: {
padding:5,
borderColor:'black',
borderWidth:1,
width:100,
marginTop:5,
},
blank: {
borderColor:'white',
borderWidth:1,
padding:5,
width:100,
marginTop:5,
},
});
You can take advantage of Flex positioning to achieve this. Also the layout can be simplified to something like:
render() {
return (
<View style={styles.container}>
<View style={styles.wrapper}>
<TextInput
style={styles.input}
placeholder='Element'
onChangeText={this.handleElement}
/>
{
this.state.show &&
<TextInput
style={styles.input}
placeholder='Key'
onChangeText={this.handleKey}
/>
}
<Button title='Add' onPress={this.onSubmit} />
</View>
</View>
)
}
The styles for the wrapper and the container elements using flex are:
wrapper: {
flex: 1,
justifyContent: 'space-between',
alignItems: 'center',
flexDirection: 'column'
},
container: {
flex: 0.5
}
The flex value of the container depends on your layout and how much space you want that element to take the screen.
I would recommend using visibility:hidden on the second TextInput. It will retain the spacing, just hide the element.

Categories

Resources