Position absolute not working inside ScrolView in React native - react-native

I was trying to position a button on the bottom right of the screen like the picture below:
So, basically I had a Scrollview with the button inside like so:
import React, { Component } from 'react'
import { ScrollView, Text, KeyboardAvoidingView,View,TouchableOpacity } from 'react-native'
import { connect } from 'react-redux'
import { Header } from 'react-navigation';
import CreditCardList from '../Components/credit-cards/CreditCardList';
import Icon from 'react-native-vector-icons/Ionicons';
import Button from '../Components/common/Button';
// Styles
import styles from './Styles/CreditCardScreenStyle'
import CreditCardScreenStyle from './Styles/CreditCardScreenStyle';
class CreditCardScreen extends Component {
render () {
return (
<ScrollView style={styles.container}>
<CreditCardList />
<TouchableOpacity style={CreditCardScreenStyle.buttonStyle}>
<Icon name="md-add" size={30} color="#01a699" />
</TouchableOpacity>
</ScrollView>
)
}
}
My styles:
import { StyleSheet } from 'react-native'
import { ApplicationStyles } from '../../Themes/'
export default StyleSheet.create({
...ApplicationStyles.screen,
container:{
marginTop: 50,
flex: 1,
flexDirection: 'column'
},
buttonStyle:{
width: 60,
height: 60,
borderRadius: 30,
alignSelf: 'flex-end',
// backgroundColor: '#ee6e73',
position: 'absolute',
bottom: 0,
// right: 10,
}
})
The problem is that the absolute positioning does not work at all when the button is inside the ScrollView. But...If I change the code to look like this:
import CreditCardScreenStyle from './Styles/CreditCardScreenStyle';
class CreditCardScreen extends Component {
render () {
return (
<View style={styles.container}>
<ScrollView >
<CreditCardList />
</ScrollView>
<TouchableOpacity style={CreditCardScreenStyle.buttonStyle}>
<Icon name="md-add" size={30} color="#01a699" />
</TouchableOpacity>
</View>
)
}
}
Then it works !! Whaat? Why? How? I don't understand why this is happening and I would appreciate any information about it.

This might be inconvenient but is just how RN works.
Basically anything that's inside the ScrollView (in the DOM/tree) will scroll with it. Why? Because <ScrollView> is actually a wrapper over a <View> that implements touch gestures.
When you're using position: absolute on an element inside the ScrollView, it gets absolute positioning relative to its first relative parent (just like on the web). Since we're talking RN, its first relative parent is always its first parent (default positioning is relative in RN). First parent, which in this case is the View that's wrapped inside the ScrollView.
So, the only way of having it "fixed" is taking it outside (in the tree) of the ScrollView, as this is what's actually done in real projects and what I've always done.
Cheers.

i suggest to use "react-native-modal".
you can not use position: 'absolute' to make elements full size in ScrollView
but you can do it by
putting that element in modal wrapper.
below are two examples. first one doesnt work but the second one works perfectly.
first way (doesnt work):
const app = () => {
const [position, setPosition] = useState('relative')
return(
<ScrollView>
<Element style={{position: position}}/>
<Button
title="make element fixed"
onPress={()=> setPosition('absolute')}
/>
</ScrollView>
)
}
second way (works perfectly):
const app = () => {
const [isModalVisible, setIsModalVisible] = useState(false)
return(
<ScrollView>
<Modal isModalVisible={isModalVisible}>
<Element style={{width: '100%', height: '100%'}}/>
</Modal>
<Button
title="make element fixed"
onPress={()=> setIsModalVisible(true)}
/>
</ScrollView>
)
}

for me this worked:
before:
<View>
<VideoSort FromHome={true} />
<StatisticShow style={{position:'absulote'}}/>
</View>
after:
<View>
<ScrollView>
<VideoSort FromHome={false} />
</ScrollView>
<View style={{position:'relative'}}>
<StatisticShow style={{position:'absulote'}}/>
</View>
</View>

Related

How do you fit an image in react native?

// How do you set the image on the top of the screen without losing the aspect ration?
[![import React, { Component } from 'react';
import { AppRegistry, View, Image, StyleSheet } from 'react-native';
export default class DisplayAnImageWithStyle extends Component {
render() {
return (
<View style={{flex:1}}>
<Image
resizeMode="contain"
style={{flex:1}}
source={{uri: 'https://i.pinimg.com/originals/ba/84/1c/ba841cc07934b508458a7faea62141a8.jpg'}}
/>
</View>
);
}
}
// Skip these lines if you are using Create React Native App.
AppRegistry.registerComponent(
'DisplayAnImageWithStyle',
() => DisplayAnImageWithStyle
);][1]][1]
// Here the liked image shows that it is not fitting well... it is not showing from the top... do you have any idea how I can set the image without any padding?
[1]: https://i.stack.imgur.com/LYNKn.png
So you might wanna use resizeMode: 'cover' with a height and width.
<Image
resizeMode="contain"
style={{ width: 200, height:220, resizeMode: 'cover'}}
source={{uri: 'https://i.pinimg.com/originals/ba/84/1c/ba841cc07934b508458a7faea62141a8.jpg'}}
/>
Here's an example https://snack.expo.io/HJTFg9tU4
Let me know if this works for you.

Create a reusable React Native Modal Component

I'm going back to basics with React Native, as I feel overwhelmed. I have been looking for an implementation of a reusable modal component. I'm looking for examples of a reusable Modal component in RN? Thanks in advance
You can find many examples of this on StackOverflow. Still, if you need example I can help you with one example. You have mentioned modal component in your question, right?
Your component will look like this with props. let the name be ModalComponent for this file.
render() {
const { isVisible, message, textValue } = this.props;
return (
<Modal
animationType="slide"
transparent={false}
isVisible={isVisible}
backdropColor={"white"}
style={{ margin: 0 }}
onModalHide={() => {}}>
<View>
<Text>textValue</Text>
<Text>message</Text>
</View>
</Modal>
);
}
so now in your js file you need to import this modalComponent and after that, you need to write as
<ModalComponent
isVisible={true}
textValue={'hi there'}
message={'trying to make a basic component modal'}/>
Hope this will help for you
EDIT:
Create seperate components that you want to render inside modal. for Ex: component1.js, component2.js, component3.js with props
component1.js:
render(){
const { textVal, message } = this.props
return (
<View>
<Text>{textVal}</Text>
<Text>{message}</Text>
</View>
)
}
now in ModalComponent
render() {
const { first, second, third, isVisible, component1Text, component1Message } = this.props;
<Modal
animationType="slide"
transparent={false}
isVisible={isVisible}
backdropColor={"white"}
style={{ margin: 0 }}
onModalHide={() => {}}>
<View>
{first && <component1
textValue= component1Text
message= component1Message />}
{second && <Component2 />}
{third && <Component2 />}
</View>
</Modal>
In this way, you can achieve it within the single modal.
You will make a component like this giving the parent component all the liberty to change it through props.
render() {
const { isVisible, message, textValue, animationType, backDropColor, style, onModalHide, children } = this.props;
return (
<Modal
animationType= {animationType || 'slide'}
transparent={transparent || false}
isVisible={isVisible || false}
backdropColor={backdropColor || "white"}
style={[modalStyle, style]}
onModalHide={onModalHide}>
{children}
</Modal>
);
}
Then in your parent component, you need to import this component like this:
import ModalComponent from '../ModalComponent'; //path to your component
<ModalComponent isVisible={true}>
<View>
//any view you want to be rendered in the modal
</View>
</ModalComponent>
I had a lot of troubles using react-native modal, sometimes i started the app and could not close it even when i set the isVisible prop to false, it is even worst on IOs, i did a research and these packages are not being maintained properly.
You will save a lot of time by using a top-level navigator like is recommended in the modal docs: https://facebook.github.io/react-native/docs/modal.
I tried https://github.com/react-native-community/react-native-modal but had the same problems because its an extension of the original react-native modal.
I suggest you to use the react-navigation modal as described here: https://reactnavigation.org/docs/en/modal.html#docsNav
You can refer the following code to write Modal component once and use multiple times.
Write once:
import React, { Component } from 'react';
import { View, Text, Button, Modal, ScrollView, } from 'react-native';
export class MyOwnModal extends Component {
constructor(props) {
super(props);
this.state = {
}
render() {
return(
<Modal
key={this.props.modalKey}
transparent={this.props.istransparent !== undefined ? true : false}
visible={this.props.visible}
onRequestClose={this.props.onRequestClose}>
<View style={{
//your styles for modal here. Example:
marginHorizontal: width(10), marginVertical: '30%',
height: '40%', borderColor: 'rgba(0,0,0,0.38)', padding: 5,
alignItems: 'center',
backgroundColor: '#fff', elevation: 5, shadowRadius: 20, shadowOffset: { width: 3, height: 3 }
}}>
<ScrollView contentContainerStyle={{ flex: 1 }}>
{this.props.children}
</ScrollView>
</View>
</Modal>
);
}
}
Now,
You can call your Modal like following example: (By doing this, you avoid re-writing the Modal and its outer styles everytime!)
Example
<MyOwnModal modalKey={"01"} visible={true} onRequestClose={() =>
this.anyFunction()} istransparent = {true}>
<View>
// create your own view here!
</View>
</MyOwnModal>
Note: If you are in using different files don't forget to import , and also you can pass the styles as props.
(You can create/customise props too based on your requirement)
Hope this saves your time.
Happy coding!
I am a contributor of react-native-use-modal.
This is an example of creating a reusable modal in a general way and using react-native-use-modal: https://github.com/zeallat/creating-reusable-react-native-alert-modal-examples
With react-native-use-modal, you can make reusable modal more easily.
This is a comparison article with the general method: https://zeallat94.medium.com/creating-a-reusable-reactnative-alert-modal-db5cbe7e5c2b

ImageBackground won't appear

I've been trying to render a background image, and it runs, but nothing appears. I'm running this through Android on Windows. This is the code below:
import React, { Component } from 'react';
import { View, Image, Text, ImageBackground } from 'react-native';
class Background extends Component {
render() {
return (
<ImageBackground
source={{uri: 'https://thumbs.dreamstime.com/b/purple-blue-textured-background-wallpaper-app-background-layout-dark-gradient-colors-vintage-distressed-elegant-78118630.jpg'}}
style={{flex: 1, width: '100%'}}
>
<View >
<Text>Test</Text>
</View>
</ImageBackground>
);
}
}
export default Background;
I'm not sure if the code just isn't properly pulling the image itself or if the styling needs to be adjusted. Thanks for the help!
Your ImageBackground component needs a height value in your style attribute. RN is picky about that.
import { ImageBackground } from 'react-native'
<ImageBackground
source={require('../assets/background.jpg')}
resizeMode={'cover'}
style={{ flex: 1, width: '100%' }}></ImageBackground>
Wrap your ImageBackground component within a Container component.
class Background extends Component {
render() {
return (
<Container>
<ImageBackground
source={{uri: 'https://thumbs.dreamstime.com/b/purple-blue-textured-background-wallpaper-app-background-layout-dark-gradient-colors-vintage-distressed-elegant-78118630.jpg'}}
style={{flex: 1, width: '100%'}}>
<View >
<Text>Test</Text>
</View>
</ImageBackground>
</Container>
);
}
}
for me only shows when i use
require()
like this post
ImageBackground not working when i call source from state
source={require( 'https://thumbs.dreamstime.com/b/purple-blue-textured-background-wallpaper-app-background-layout-dark-gradient-colors-vintage-distressed-elegant-78118630.jpg')}
(i tried to import image and call inside source but don't appears, even declaring in style height and width, only after use require(), why? i don't know)

React native textinput multiline is not being pushed up by keyboard

I have a TextInput with multiLine true. However, after two lines the text disappear behind the keyboard. I have tried wrapping the TextInput in KeyboardAvoidingView, but it doesn't work.
The keyboard does push up the TextInput when I unfocus the TextInput and then click on the bottom line. Any idea how I can make the last line of the TextInput stay on top of the keyboard?
The code:
<View style={styles.descriptionFlexStyle}>
<Text
style={[
styles.headerTextStyle,
{ marginTop: Window.height * 0.04 }
]}> Please fill in a reason </Text>
<ScrollView>
<TextInput
style={styles.reasonTextInput}
placeholder="Reason"
value={reasonText}
multiline={true}
onChangeText={input =>
this.setState({
reasonText: input
})
}
underlineColorAndroid="transparent"
ref="reasonTextInput"
/>
</ScrollView>
</View>
hello my dear you must use KeyboardAvoidingView Component from React-Native and put a behavior on it like below :
<KeyboardAvoidingView behavior={'postion' || 'height' || 'padding'}>
<View style={styles.descriptionFlexStyle}>
<Text
style={[
styles.headerTextStyle,
{ marginTop: Window.height * 0.04 }
]}> Please fill in a reason </Text>
<ScrollView>
<TextInput
style={styles.reasonTextInput}
placeholder="Reason"
value={reasonText}
multiline={true}
onChangeText={input =>
this.setState({
reasonText: input
})
}
underlineColorAndroid="transparent"
ref="reasonTextInput"
/>
</ScrollView>
</View>
</KeyboardAvoidingView>
This answer may be a little too late. However, I have found a workaround without using the KeyboardAvoidingView component. A ScrollView could be used instead to scroll the multiline TextInput to the top to have the 'keyboard avoiding' effect. I would use the ref measure() method to get the top y value of the TextInput, before using the scrollTo() method to scroll the TextInput directly to the top of the screen, effectively avoiding the keyboard.
import React, { useRef } from "react";
import { ScrollView, TextInput, View } from "react-native";
export default function Test() {
const scrollViewRef = useRef(null);
const viewRef = useRef(null);
const handleFocus = () => {
viewRef.current.measure((x, y) => {
scrollViewRef.current.scrollTo({ x: 0, y });
});
};
return (
<ScrollView ref={scrollViewRef}>
{/* View to fill up space */}
<View
style={{
width: "80%",
height: 600,
}}
/>
<View ref={viewRef}>
<TextInput
onFocus={handleFocus}
multiline={true}
style={{
width: "80%",
height: 100,
backgroundColor: "whitesmoke",
alignSelf: "center",
}}
/>
{/* View to fill up space */}
<View
style={{
width: "80%",
height: 600,
}}
/>
</View>
</ScrollView>
);
}
Ok i have finally solved it using "KeyboardAvoidingView". I did two things. First i removed the height on my TextInput and then i set the behavior attribute on the "KeyboardAvoidingView" to "padding". Works perfect for me now. Let me know if this help! :)

React native: Cannot add a child that doesn't have a YogaNode or parent node

Just started learning react-native,
I have created one separate file flexdemo.js and created component as below:
import React, { Component } from 'react';
import { View } from 'react-native';
export default class FlexibleViews extends Component {
render() {
return (
<View style={{ flex: 1 }}>
<View style={{ flex: 1, backgroundColor: "powderblue" }}> </View>
<View style={{ flex: 2, backgroundColor: "skyblue" }}> </View>
<View style={{ flex: 3, backgroundColor: "steelblue" }}> </View>
</View>
);
}
}
and App.js file is as below:
import React, { Component } from 'react';
import {
AppRegistry,
Platform,
StyleSheet,
Text,
View, Image
} from 'react-native';
// import Bananas from './src/banana';
// import LotsOfStyles from './src/styledemo'
import FlexibleViews from './src/flexdemo';
export default class App extends Component {
render() {
return (
// <Bananas name = "Tapan"/>
<View>
<FlexibleViews />
</View>
);
}
}
That gives me this error:
Now if I try to run the code by adding flexdemo.js code into App.js then everything works fine.
Changed The App.js like this:
import React, { Component } from 'react';
import { AppRegistry, View } from 'react-native';
export default class FlexDimensionsBasics extends Component {
render() {
return (
// Try removing the `flex: 1` on the parent View.
// The parent will not have dimensions, so the children can't expand.
// What if you add `height: 300` instead of `flex: 1`?
<View style={{flex: 1}}>
<View style={{flex: 1, backgroundColor: 'powderblue'}} />
<View style={{flex: 2, backgroundColor: 'skyblue'}} />
<View style={{flex: 3, backgroundColor: 'steelblue'}} />
</View>
);
}
}
Remove comments inside component.
I want to give a more general answer here, because there can be several reasons for the issue returning the same error message. The three I have seen the most:
1. Comments might be the cause. But instead of removing comments make
them work:
In the return()-part, variables need to be wrapped in {} like
{this.state.foo} so wrapping the comments works fine...
return(
<Text> This works {/* it really does */}</Text>
);
...as long as they are not the first or last element in the return statement:
return(
{/* This fails */}
<Text> because the comment is in the beginning or end </Text>
{/* This also fails */}
);
2. Conditional rendering might be the cause. If myCheck is undefined or
an empty string this can fail:
const myCheck = ""; /* or const myCheck = undefined */
return(
{myCheck && <MyComponent />}
);
but adding double negation !! works:
const myCheck = ""; /* or const myCheck = undefined */
return(
{!!myCheck && <MyComponent />}
);
3. Whitespaces (or actually any strings) within a component can cause
this, if not in a <Text>-Component:
Text in a View for example:
/* This fails */
return(
<View>it really does</View>
);
But also the tiny space between two components:
/* <View>*Space*<Text> fails: */
return(
<View> <Text>it really does</Text> </View>
);
But works if in a newline:
return(
<View>
{/* This works */}
<Text>surprisingly it does</Text>
</View>
);
Unfortunately these pitfalls do not always lead to errors. Sometimes they work. I guess this depends on which of all those many tools/libraries/components you use and their versions in your app.
I was able to reproduce the issue with the code you provided. The solution is twofold:
In your flexdemo.js file you should remove the whitespaces from within the <View> tags. They are considered as text, and text is only allowed inside a <Text> component. I'd recommend making your <View> tags self closing until they have some content, to stay away from this issue in the future, like so:
import React, { Component } from 'react';
import { View } from 'react-native';
export default class FlexibleViews extends Component {
render() {
return (
<View style={{ flex: 1 }}>
<View style={{ flex: 1, backgroundColor: 'powderblue' }} />
<View style={{ flex: 2, backgroundColor: 'skyblue' }} />
<View style={{ flex: 3, backgroundColor: 'steelblue' }} />
</View>
);
}
}
This will render your components but still be faulty, as you wont see anything on the screen.
To get your flexible shades of blue to appear you'll either have to add flex to the <View> component in your App.js file or(depending on what your next steps are, I guess) remove it and render your <FlexibleViews> as the root component, since it is basically a <View> component with some children anyway.
If you have if else statement in your render() function use !! like this:
{!! (this.state.your_state) &&
<View>
<Text>Your Text</Text>
</View>
}
instead of:
{(this.state.your_state) &&
<View>
<Text>Your Text</Text>
</View>
}
I downgrade react native version, then I got a different error, basically what it was I had a simple string within a view, something like this:
<View>
MyComponent
</View>
I had to wrap the string with a text component like this:
<View>
<Text>MyComponent</Text>
</View>
hope that helps
<View style={{ flex: 1 }}>
<Text style={{ flex: 1, backgroundColor: "powderblue" }}> </Text>
<Text style={{ flex: 2, backgroundColor: "skyblue" }}> </Text>
<Text style={{ flex: 3, backgroundColor: "steelblue" }}> </Text>
</View>
Make use Component hierarchy should be maintain, for example all components like Text, ListView, TextInput etc should be wrapped inside the parent component that is View.
lets see the below example :
< View >
< Text >
CORRECT
< / Text >
< / View >
Make sure all the Component tag should be closed properly.
Make sure unnecessary semicolons should be removed from the react native layout components & functions.
https://www.skptricks.com/2018/08/react-native-cannot-add-child-that.html
This error is usually from one of below mistakes
Remove unnecessary comments and remove comments from return function.
check for proper variable name.
check for unintended semicolon or any wrong syntax
Delete the comment in the return block "// "
I encountered the same problem when I accidentally add a ';' in the return block, the iOS is work well, but the Android has this bug information
In my case I had small () brackets around one of my view which was causing error.
({renderProgress()})
Removing small brackets worked for me.
{renderProgress()}
In my case I had a condition in my render function that resulted in evaluating 0.
It seems that 0 && 'some jsx' breaks in newer versions of react native.
Error Example:
render(){
return <View>
{this.state.someArray.length && <View>...</View>}
</View>
}
Although this should be valid javascript and works in react since 0 is falsey, It crashes in react native, not sure why but it works with a little refactoring as:
Working Example:
render(){
return <View>
{this.state.someArray && this.state.someArray.length> 0 &&
<View>...</View>}
</View>
}
Remove semi-colon when rendering a method in
<View style={styles.container}>
{this.renderInitialView()} //semi-color should not be here
</View>
I have encountered the same issue just now and solved it by removing the comments that I have made while editing the project in android studio and over there the comment's shorotcut just adds /* and */ but actually for react native the commented code should be enclosed with starting and end of curly braces, for example following would be an invalid comment:
/*<Text style={styles.pTop}>
{
this.state.response.map((index, value) => {
return index.title;
})
}
</Text>*/
And the following will be a valid one:
{/*<Text style={styles.pTop}>
{
this.state.response.map((index, value) => {
return index.title;
})
}
</Text>*/}
you see there is just one minor difference of enclosing the comment in curly braces.
This error also occurs if you have comments in your render() return() function. Remove all comments in your return function when rendering JSX
In my case I had written <TextInput> in the <Text> tag.
Below is wrong. It will give error for child.
<text>
<TextInput style={styles.textinput}
textcolor
placeholder = 'user id'
placeholderTextColor = 'gray'
/>
</Text>
solution.
<Text> hello </Text>
<TextInput style={styles.textinput}
textcolor
placeholder = 'user id'
placeholderTextColor = 'gray'
/>
you have to write separate tag.
So any tag you have written in another tag this error can come.