React Native - Parent View to wrap the child view - javascript

I have a view having text inside it. The component looks like this:
MyComponent = () => {
return (
<View style={styles.viewStyle}>
<Text style={styles.textStyle}>My Text</Text>
</View>
);
}
const styles = {
viewStyle: {
backgroundColor: '#006699',
height: 40,
justifyContent: 'center',
alignItems: 'center',
},
textStyle: {
color: '#000000',
fontSize: 16,
}
}
When this component gets used, I want my View to have a custom width such that it just wraps my text. Here's the visual clue:

It's about the original design of Layout with Flexbox.
You can make it work by either add flexDirection: 'row' to it's parent view (so it will stretch automatically related to <Text /> width),
<View style={{flex: 1, flexDirection: 'row'}}>
<View style={styles.viewStyle}>
<Text style={styles.textStyle}>My Text</Text>
</View>
</View>
or give width to it directly.
<View style=[{styles.viewStyle}, {width: 50}]>
<Text style={styles.textStyle}>My Text</Text>
</View>
Result of option 1:

Related

Is there a way to make a sized and functional FlatList inside a Modal?

Good evening!
I have been trying to create a modal with a scrollable FlatList inside, but such FlatList should have its height size reduced. The modal is going to search a wide list of airports, so basically a lot data might be shown, hence why FlatList is the best tool for this occasion. Basically, the modal screen would look like this picture below:
However, I can't make the scroll inside FlatList work no matter what. Here is the code, with the FlatList that is somewhat functional, but it has a warning:
const styles = StyleSheet.create({
modalContainer: {
backgroundColor: 'rgba(50,50,50,0.6)',
flex: 1,
justifyContent: 'center',
alignItems: 'center',
},
modalActivityContainer: {
backgroundColor: colors.colorWhite,
borderColor: colors.colorLightBlack,
borderWidth: 2,
borderRadius: 20,
padding: props.padding ? Number(props.padding) : 10,
maxWidth: '85%',
},
modalHeader: {
flexDirection: 'row',
justifyContent: 'center',
},
headerAirportModal: {
backgroundColor: colors.colorGrey,
borderTopRightRadius: 20,
borderTopLeftRadius: 20,
paddingHorizontal: 5,
paddingVertical: 10,
width: '100%',
justifyContent: 'center',
},
searchAirportBarContainer: {
backgroundColor: colors.colorWhite,
height: 40,
},
...
<Modal
onRequestClose={() => props.onRequestClose()}
animationType="fade"
transparent
visible={props.showModal}>
<TouchableWithoutFeedback
onPress={() => {
props.onRequestClose();
}}>
<View style={styles.modalContainer}>
<TouchableWithoutFeedback>
<View style={styles.modalActivityContainer}>
<View style={styles.modalHeader}>
<View style={styles.headerAirportModal}>
<Item style={styles.searchAirportBarContainer} rounded>
<Icon
style={styles.iconSearchAirport}
type="FontAwesome5"
name="search"
/>
<Input
style={styles.searchAirportBarText}
placeholderTextColor={colors.colorLightBlack}
placeholder="Search by Airport, Country or City"
/>
</Item>
</View>
</View>
<View>
<View style={styles.modalHeader}>
<Grid style={styles.headerAirportModalBackground}>
<Text style={styles.headerAirportModalText}>Latest Searches</Text>
<TouchableOpacity style={styles.clearButtonLatestContainer}>
<View>
<Text style={styles.clearButtonAirport}>Clear</Text>
</View>
</TouchableOpacity>
</Grid>
</View>
</View>
<View style={{maxHeight: 250}}>
<ScrollView>
<View onStartShouldSetResponder={() => true}>
<FlatList
data={airportElements}
renderItem={renderAirportItem}
keyExtractor={(item) => item.id}
/>
</View>
</ScrollView>
</View>
<Button
backgroundColor={colors.colorRed}
alignSelf="stretch"
buttonStyle={styles.finishButton}
onPress={() => {
setModalSelectAirport(false);
}}>
Cancel
</Button>
</View>
</TouchableWithoutFeedback>
</View>
</TouchableWithoutFeedback>
</Modal>
If I use the FlatList inside the ScrollView like shown above, the code works as intended. However, I got this warning:
VirtualizedLists should never be nested inside plain ScrollViews
with the same orientation - use another VirtualizedList-backed
container instead.
Because of that, I can't use FlatList properly. Also, I have managed to make it work with .map, but it was advised to not use it as I am going to load a list with a lot of elements and that might cause lag.
I have managed to implement FlatList in another way like this:
<View
style={styles.airportLatestSearchListContainer}>
<FlatList
contentContainerStyle={styles.airportLatestSearchlist}
data={airportElements}
renderItem={renderAirportItem}
keyExtractor={(item) => item.id}
/>
</View>
This, however, prevents the user to scroll. The list remains static and the user can't scroll at all.
I have tried using {flex: 1, flexGrow: 1} in the parent View and FlatList itself, both don't work at all, even inside the FlatList container or the style.
Can someone please help me with this one? I really appreciate the time and effort! Thanks!

React native KeyboardAvoidingView not moving correctly

I have a TextInput that when pressed gets covered by the keyboard. So I wrapped it in a KeyboardAvoidingView. But regardless of the behavior that I set for this view, the TextInput won't move above the keyboard. Using position as the behavior moves the TextInput but only half way above the keyboard, while the other two don't seem to work at all.
I also tried wrapping my entire component with a KeyboardAvoidingView, but doing so breaks the entire layout.
Can anyone help me? I never managed to get KeyboardAvoidingView to work for me and now I really need it. Thanks in advance!
Here is my component. Also worth mentioning is that this component is top level(well, almost top level since it's wrapped in a Router)
const { height, width } = Dimensions.get('screen')
const style = StyleSheet.create({
main: {
height,
width,
flexDirection: 'column',
},
iconSelecter: {
width,
height: 196,
alignItems: 'center',
justifyContent: 'center',
backgroundColor: Colors.primary,
marginTop: 32
},
icon: {
height: 164,
width: 164,
},
saveButton: {
width: 96,
height: 96,
borderRadius: 100,
backgroundColor: Colors.secondary,
alignItems: "center",
justifyContent: "center",
alignSelf: 'center',
position: 'absolute',
bottom: 96 + 32
},
saveIcon: {
height: 54,
width: 54,
},
textInputWrapper: {
borderBottomColor: Colors.textInputBorder,
width: 288,
borderBottomWidth: 1,
alignSelf: 'center',
marginTop: 96,
height: 48,
},
textInput: {
fontWeight: "300",
fontSize: 14,
margin: 0
},
hintWrapper: {
alignSelf: 'center',
marginTop: 4
},
hint: {
fontSize: 12,
fontFamily: "Roboto-Thin",
fontStyle: 'normal',
}
})
const CreateActivity = ({ goBack }: NavigationProps) => {
//////////////////////////////
//State and logic
///////////////
return (
// TODO: Add touchable opacity to dismiss keyboard
<View style={style.main}>
<Appbar title="New activity" canGoBack goBack={goBack} />
<View style={{ flex: 1 }}>
<View style={style.iconSelecter}>
<GestureRecognizer onSwipeLeft={nextIcon} onSwipeRight={lastIcon}>
<Image style={style.icon} source={icons[currentIconIndex]?.file}></Image>
</GestureRecognizer>
</View>
<View style={style.hintWrapper}>
<Text style={style.hint}>Swipe to cycle through the icons</Text>
</View>
<KeyboardAvoidingView>
<View style={style.textInputWrapper}>
<TextInput style={style.textInput} placeholder={"Give this activity a name"} value={name} onChangeText={setName}></TextInput>
</View>
</KeyboardAvoidingView>
<TouchableNativeFeedback onPress={createActivity} background={TouchableNativeFeedback.Ripple("#fff", true)}>
<View style={style.saveButton}>
<Image style={style.saveIcon} source={require("../../assets/icons/light/save.png")}></Image>
</View>
</TouchableNativeFeedback>
</View>
</View>
)
}
export default CreateActivity;
I suggest that you to try wrap all the content of the screen in <KeyboardAvoidingView /> (or make it one of the outermost elements), otherwise it only will slide up its children (the View and the TextInput) leaving the rest of the content in its original position, making the layout look overlaped and weird. If you do that, the value "position" should work fine.
Something like this:
<View style={style.main}>
<Appbar title="New activity" canGoBack goBack={goBack} />
<KeyboardAvoidingView behavior="position" >
<View style={{ flex: 1 }}> // --> Remove flex: 1 if you experience some issue with the positioning
<View style={style.iconSelecter}>
<GestureRecognizer onSwipeLeft={nextIcon} onSwipeRight={lastIcon}>
<Image style={style.icon} source={icons[currentIconIndex]?.file}></Image>
</GestureRecognizer>
</View>
<View style={style.hintWrapper}>
<Text style={style.hint}>Swipe to cycle through the icons</Text>
</View>
<KeyboardAvoidingView>
<View style={style.textInputWrapper}>
<TextInput style={style.textInput} placeholder={"Give this activity a name"} value={name} onChangeText={setName}></TextInput>
</View>
</KeyboardAvoidingView>
<TouchableNativeFeedback onPress={createActivity} background={TouchableNativeFeedback.Ripple("#fff", true)}>
<View style={style.saveButton}>
<Image style={style.saveIcon} source={require("../../assets/icons/light/save.png")}></Image>
</View>
</TouchableNativeFeedback>
</View>
</KeyboardAvoidingView>
</View>
Also see the comment in the code above. Check if you really need to use of flex: 1 in all the outer wrapper elements, and take a look to the height you are setting in the style.main based on dimentions. I don't think that it is necesary and I think it could lead to some measure issues if you fix the height of the parent container.
EDIT:
I was just digging in react-native docs and I realize that there is a zIndex that you could use to avoid ablsolute positioning. It is a relative style prop so it needs to be set between sibling views, like this:
export default class MyComponent extends React.Component {
render() {
return (
<View>
<View style={[styles.appbarShape, styles.appbarZIndex]} ><Text>Header</Text></View>
<KeyboardAvoidingView behavior="position" style={styles.contentZIndex}>
{other children}
<TextInput placeholder="enter text"/>
</KeyboardAvoidingView>
</View>
);
}
}
const styles = StyleSheet.create({
appbarShape: {
height: 80,
width: Dimensions.get('window').width,
justifyContent: 'center',
alignSelf: "stretch",
backgroundColor: "#FFF"
},
appbarZIndex: {
zIndex: 3,
},
contentZIndex: {
zIndex: 0
}
});
Since the view that represents the appbar has a greater zIndex it shows up over the ones with a lower zIndex
Check this out working in this snack https://snack.expo.io/5VXAcw4Y0
Docs: https://reactnative.dev/docs/layout-props
Hope it helps!
Use react-native-keyboard-aware-scroll-view
<KeyboardAwareScrollView extraHeight={135} enabledOnAndroid={true}
extraScrollHeight={70} style={styles.mainContainer}
automaticallyAdjustContentInsets={true}
enableOnAndroid={true}
keyboardShouldPersistTaps='handled'
scrollEnabled={true} >
//your form
</KeyboardAwareScrollView>
const styles = StyleSheet.create({
mainContainer: { flex: 1, marginHorizontal: 15, marginVertical: 15 },
});

Nested Text, Vertical Align not working - React Native

Ok, Let's make this simple. I've two Text components, one inside another. The first Text has fontSize of 60, and the nested one has fontSize of 20. As the font size varies, the nested Text sits base aligned. I want the nested Text vertically center aligned with the parent one.
Code
// #flow
import React, { Component } from 'react';
import { Text } from 'react-native';
type PropTypes = {}
export default class SampleVC extends Component<PropTypes> {
render() {
return (
<Text style={{ fontSize: 60 }}>
Big Text
<Text style={{ fontSize: 20 }}>Small Text</Text>
</Text>
);
}
}
Current Output
Needed Output
I know this is a simple scenario, but as am new to react native , i can't figure it out. I've searched all over the web,but couldn't find any helpful resource.
It's not possible to achieve what you're trying using just nested Text.
The Only option, use a View to wrap your texts like,
<View style={{ flexDirection: 'row', alignItems: 'center' }} >
<Text style={{ fontSize: 60 }}>Big Text</Text>
<Text style={{ fontSize: 20 }}>Small Text</Text>
</View>
And if you want to use it often, create your own custom component for the above like,
function CustomNextedText (props) {
return (
<View style={{ flexDirection: 'row', alignItems: 'center' }} >
<Text style={{ fontSize: 60 }}>{props.bigText}</Text>
<Text style={{ fontSize: 20 }}>{props.smallText}</Text>
</View>
);
}
Use it anywhere like any other react-native component,
<CustomNextedText bigText='Big Text' smallText='Small Text'/>
Hope it helps.
You can wrap nested Text in a View but nested View must have width and height. If you do not have any problem with this constraint, this is a good solution.
<Text style={{ fontSize: 60 }}>
Big Text
<View style={{ height:40, width:100, justifyContent: 'center', alignItems: 'center' }}>
<Text style={{ fontSize: 20 }}>Small Text</Text>
</View>
</Text>
you can also define the smallText lineHeight to match the bigText:
render() {
return (
<Text style={{ fontSize: 60 }}>
Big Text
<Text style={{ fontSize: 20, lineHeight:60 }}>
Small Text
</Text>
</Text>
);
}
Since React-Native v0.63 you can render <View/> inside <Text/>, without providing explicit dimensions for the View. Release Notes
With the accepted answer, if your Big Text is long enough to span multiple lines, the small text will be vertically centered to the entire block of Big Text, rather than a specific line.
So here's an update to #Ali S's answer using the new functionality. Height is still required in order to vertically center the nested text, so it is set to the fontSize of the Big Text. Width can be omitted, so the length of the small text can now be dynamic.
function BigSmallText(props) {
let bigFontSize = 40;
return (
<Text
style={{
fontSize: bigFontSize,
lineHeight: bigFontSize,
}}>
A very long sentence that spans multiple lines
<View
style={{
flexDirection: 'row',
alignItems: 'center',
height: bigFontSize,
}}>
<Text
style={{
fontSize: 14,
paddingLeft: 10,
}}>
SMALL TEXT
</Text>
<Text
style={{
fontSize: 6,
paddingLeft: 10,
}}>
TINY TEXT
</Text>
</View>
</Text>
);
}
You can add both Text into View.
<View style={{alignItems: 'center', justifyContent: 'center'}}>
<Text style={{ fontSize: 60, height:'100%' }}>Big Text</Text>
<Text style={{ fontSize: 20, height:'100%' }}>Small Text</Text>
</View>
< View style={{flexDirection:'column'}}>
<View style={{alignContent:'center'}}>
<Text style={{fontSize:60}}>{props.bigText}</Text>
</View>
<View style={{alignContent:'center'}} >
<Text style={{fontSize:20}}>{props.smallText}</Text>
</View>
< /View>
That seems odd, but here is something that seems to do the job for me (using #Ali SabziNezhad's suggestion). It allows to share text props (like color) and alignement (center in this particular case)
function Component() {
return (
<CenterText style={{color: 'red'}}>
Centered <Text style={{fontSize: 50}}>text</Text>
</CenterText>
);
}
export function CenterText({children, ...otherProps}: Text['props']) {
return (
<Text {...otherProps}>
<View
style={{flexDirection: 'row', alignItems: 'center'}}
children={children}
/>
</Text>
);
}
We could event have a more generic alignment text component:
export function AlignedText({children, alignItems, ...otherProps}: AlignedTextProps) {
return (
<Text {...otherProps}>
<View
style={{flexDirection: 'row', alignItems: alignItems}}
children={children}
/>
</Text>
);
}
type Alignment = 'baseline' | 'center' | 'flex-end' | 'flex-start' | 'stretch';
type AlignedTextProps = Text['props'] & {alignItems: Alignment};
Which we can then use to define CenterText:
export function CenterText(props: TextProps) {
return <AlignedText alignItems='center' {...props} />;
}
Or directly as:
function Component() {
return (
<AlignedText style={{color: 'red'}} alignItems='center'>
Centered <Text style={{fontSize: 50}}>text</Text>
</AlignedText>
);
}

React Native - Swipe to hide and show new content

I am creating list of items on react native app. I want to make swipe to left and right every item of this list. So when I swipe to left I want to hide Views that was rendered and show new elements. Also when I swipe to right I want to display other elements that will be different from that element that will be rendered when I swipe left. I found this library called "react-native-swipe-gestures" but I can't figure out how to display and hide elements with it. I declared some items but when I try to display it i got an error that "can't find variable 'item'" maybe you will have some explain to me how I should use it to actually get working swipe left and right.
import React, {Component} from 'react';
import {
ScrollView,
Text,
View,
Image,
Button
} from 'react-native';
import GestureRecognizer, {swipeDirections} from 'react-native-swipe-gestures';
import {List, ListItem} from "react-native-elements";
class Offers extends Component {
constructor(props) {
super(props);
this.state = {
myText: '',
gestureName: 'none',
icons: '',
guardian: '',
area: '',
rooms: '',
floor: '',
market: '',
year: '',
pricePerMeter: '',
};
}
onSwipeRight(gestureState) {
this.setState({myText: 'You swiped right!'});
}
onSwipe(gestureName, gestureState) {
const {SWIPE_LEFT, SWIPE_RIGHT} = swipeDirections;
this.setState({gestureName: gestureName});
switch (gestureName) {
case SWIPE_LEFT:
this.setState({backgroundColor: 'blue'});
break;
case SWIPE_RIGHT:
this.setState({backgroundColor: 'yellow'});
break;
}
}
onSwipeLeft(gestureState) {
this.setState({
guardian: item.offerGuardian, //items from const offers
area: item.offerArea,
floor: item.offerFloor,
rooms: item.offerRooms,
market: item.offerMarket,
year: item.offerYear,
pricePerMeter: item.offerPricePerMeter,
})
}
render() {
const config = {
velocityThreshold: 0.3,
directionalOffsetThreshold: 80
};
const offers = [
{
offerNumber: 'TEST912697',
offerLocation: 'Warszawa Białołęka',
offerStreet: 'ul. Bruszewska',
offerType: 'Mieszkanie',
offerStatus: 'Akt. Wewnętrzna',
offerStatusColor: '#0FBEB2',
offerAddDate: '2017-09-20 12:08:06',
offerPrice: '2 450 000',
photo: 'https://static.pexels.com/photos/164516/pexels-photo-164516.jpeg',
offerGuardian: 'Adam Borek',
offerTransactionType: 'sprzedaż',
offerArea: '50 m2',
offerRooms: '2 pokoje',
offerFloor: '1 z 2',
offerYear: '2005 rok',
offerMarket: 'rynek pierwotny',
offerPricePerMeter: '5000 zł/m2'
},
];
return (
<ScrollView>
<View style={{
flexDirection: 'row',
justifyContent: 'flex-end',
alignItems: 'flex-end'
}}>
<View style={{marginRight: 20, marginTop: 10}}>
<Button title="akcje"/>
</View>
</View>
{offers.map((item, i) => (
<View key={i}>
<List>
<GestureRecognizer
onSwipe={(direction, state) => this.onSwipe(direction, state)}
onSwipeLeft={(state) => this.onSwipeLeft(state)}
onSwipeRight={(state) => this.onSwipeRight(state)}
config={config}
style={{
flex: 1,
backgroundColor: this.state.backgroundColor
}}
>
<ListItem
roundAvatar
subtitle={
<View style={{flexDirection: 'row'}}>
<View>
<Text>{this.state.myText}</Text>
<Text>{this.state.guardian}</Text>
<Text>{this.state.area}</Text>
<Text>{this.state.floor}</Text>
<Text>{this.state.market}</Text>
<Text>{this.state.year}</Text>
<Text>{this.state.pricePerMeter}</Text>
<Image source={require('../../gfx/lel.jpg')}
style={{
height: 100,
width: 150
}}/>
</View>
<View style={{
marginLeft: 5,
flexDirection: 'row',
flexWrap: 'wrap'
}}>
<View style={{width: 140}}>
<Text>
{item.offerLocation}
{"\n"}
{item.offerStreet}
{"\n"}
{item.offerType} na {item.offerTransactionType}
{"\n"}
{item.offerNumber}
</Text>
</View>
<View>
<View style={{
justifyContent: 'flex-end',
width: 95,
height: 30,
backgroundColor: item.offerStatusColor
}}>
<Text style={{color: '#fff', textAlign: 'center'}}>
{item.offerStatus}
</Text>
</View>
<View style={{
flexDirection: 'column',
alignItems: 'flex-end',
flexWrap: 'wrap'
}}>
<Text style={{fontSize: 20}}>
{"\n"}
{"\n"}
{item.offerPrice}
</Text>
</View>
</View>
</View>
</View>
}
onPress={() => this.props.navigation.navigate('OffersDetails')}
/>
</GestureRecognizer>
</List>
</View>
))}
</ScrollView>
)
}
}
export default Offers;
I would recommend trying out this libray react-native-swipe-list-view. It is well documented and easy to use for any type of swipable row. https://github.com/jemise111/react-native-swipe-list-view
The basic concept is that you have one element in front of a hidden element. When you swipe it just reveals the hidden element below.

React-native Scrollview not work

I've the following layout, and it need scroll when data is greater of screen:
Image:
Code:
export default () => (
<Container hasNavBar={false}>
<View style={{flex: 1}}>
<View style={Styles.container}>
<View style={{
flex: 1, backgroundColor: 'red',
alignItems: 'center',
justifyContent: 'center',
}}>
<Text>Area 1</Text>
</View>
<View style={{
flex: 2, backgroundColor: 'yellow',
alignItems: 'center',
justifyContent: 'center',
}}>
<Text>Area 2</Text>
</View>
</View>
</View>
</Container>
);
Following the documentation of react-native for add scroll I need create a wraper of my layout using ScrollView component, but when added scrollView component my layout broke:
Image:
Code:
export default () => (
<Container hasNavBar={false}>
<ScrollView style={{flex: 1}}>
<View style={Styles.container}>
<View style={{
flex: 1, backgroundColor: 'red',
alignItems: 'center',
justifyContent: 'center',
}}>
<Text>Area 1</Text>
</View>
<View style={{
flex: 2, backgroundColor: 'yellow',
alignItems: 'center',
justifyContent: 'center',
}}>
<Text>Area 2</Text>
</View>
</View>
</ScrollView>
</Container>
);
Container Component
<View style={flex: 1}>
{this.props.children}
<DropdownAlert
closeInterval={10000}
updateStatusBar={false}
ref={(ref) => this.dropdown = ref}
onClose={() => null}/>
</View>
How i solve it ?
After re-reading the question with better understanding of your complete code it became obvious that the quickest fix would be to define minHeight on Area 1 and Area 2's views. We can calculate it from window's Dimensions. This allows you to obtain the 33%/66% ratio with minimal content and expand either Area as needed with additional content.
Place this at the top of render():
const { height } = Dimensions.get('window');
Add to Area 1's style
minHeight: height / 3
And to Area 2's style
minHeight: (height / 3) * 2

Categories