Error with invariant violation: Maximum update depth exceeded - react-native

I am a beginner in react native and I am trying to make a quiz app by using states and functions to check if the button pressed is the correct option based on the word given. However, I have received this error about invariant violation: Maximum update depth exceeded, could this be due to the way I use onPress?
import React, {Component} from 'react';
import {
View,
Text,
SafeAreaView,
TouchableOpacity,
Image,
ScrollView,
StyleSheet,
} from 'react-native';
import {color} from 'react-native-reanimated';
import Ionicons from 'react-native-vector-icons/Ionicons';
import {createAppContainer} from 'react-navigation';
import {createBottomTabNavigator} from 'react-navigation-tabs';
import {createStackNavigator} from 'react-navigation-stack';
const styles = StyleSheet.create({
progressbar: {
width: 218,
height: 24,
borderRadius: 12,
borderColor: 'grey',
borderWidth: 1,
marginTop: 70,
paddingRight: 79,
paddingLeft: 79,
},
words: {
fontFamily: 'Arial',
fontSize: 85,
fontWeight: 'bold',
},
image: {width: 345, height: 391, borderRadius: 50, marginTop: 31},
button: {width: 100, height: 80, borderRadius: 29, marginHorizontal: 5},
});
export default class quizC extends React.Component {
state = {
progress: 0,
progressbar: 0,
progressbarwidth: 0,
words: '',
imagesource: '',
option: 0,
option1: '',
option2: '',
option3: '',
correctoption: 0,
score: 0,
};
_updateProgress() {
switch (this.state.imagesource) {
case 1:
this.setState({words: 'c_t'});
this.setState({progressbarwidth: 109});
this.setState({correctoption: 2});
this.setState({option1: 'c'});
this.setState({option2: 'a'});
this.setState({option3: 't'});
//return cat
break;
case 2:
this.setState({words: 'do_'});
this.setState({progressbarwidth: 218});
this.setState({correctoption: 3});
this.setState({option1: 'd'});
this.setState({option2: 'o'});
this.setState({option3: 'g'});
//return dog
break;
}
}
_checkcorrectans() {
if (this.state.option == this.state.correctoption) {
this.setState(prevState => ({progress: prevState.progress + 1}));
this.setState(prevState => ({score: prevState.score + 1}));
this.setState({imagesource: this.state.progress});
} else {
this.setState(prevState => ({progress: prevState.progress + 1}));
this.setState({imagesource: this.state.progress});
}
}
option1() {
this.setState({option: 1});
this._checkcorrectans();
this._updateProgress();
}
option2() {
this.setState({option: 2});
this._checkcorrectans();
this._updateProgress();
}
option3() {
this.setState({option: 3});
this._checkcorrectans();
this._updateProgress();
}
render() {
return (
<SafeAreaView>
<View style={styles.progressbar}>
<View
style={{
height: 24,
borderRadius: 12,
backgroundColor: 'green',
width: this.state.progressbarwidth,
}}
/>
</View>
<View style={{alignItems: 'center', marginTop: 12}}>
<Text style={styles.words}>{this.state.words}</Text>
</View>
<View style={styles.image}>
<Image src={this._updateProgress()} />
</View>
<View style={{paddingLeft: 23, paddingRight: 23, flexDirection: 'row'}}>
<TouchableOpacity onPress={this.option1()}>
<View style={styles.button}>
<Text>{this.state.option1}</Text>
</View>
</TouchableOpacity>
<TouchableOpacity onPress={this.option2()}>
<View style={styles.button}>
<Text>{this.state.option2}</Text>
</View>
</TouchableOpacity>
<TouchableOpacity onPress={this.option3()}>
<View style={styles.button}>
<Text>{this.state.option3}</Text>
</View>
</TouchableOpacity>
</View>
</SafeAreaView>
);
}
}

Try using
onPress={() => this.option1()} which is an anonymous function first and the calls option1 or onPress={ this.option1} . These will prevent re-rendering.
This error is due to when you call onPress={this.option1()} , it calls the function and causes the app to re-render which again causes function to be invoked, and hence an infinite loop. The best way would be calling it directly without parentheses onPress={this.option1} or create an anonymous function onPress={() => this.option1()}, which gets executed only once
hope it helps. feel free for doubts

Replace all of onPress method
from:
onPress={this.option1()}
To :
onPress={() => this.option1()}

Related

How to make a countdown timer in react native?

I have to make a countdown timer in an react-native app but i dont know how, i already looked it up and and found some librarys such as react-native-countdown component but it didnt worked as id like, and got some other solutions like setInterval but i dont know how to implement it in my code and make it display on the screen as in the images below:
The time goes from 00:00 to 60:00 (MM:SS) as the user slides the bar, that changes the number 05:00 by 05:00, ive already done that but with a static number, i couldnt make it countdown.
Heres how my code is looking right now:
import { useNavigation } from '#react-navigation/core';
import React, { useEffect, useState } from 'react';
import { SafeAreaView, Text, Image, TouchableOpacity, StyleSheet, Dimensions, TextInput, KeyboardAvoidingView, Platform, View } from 'react-native';
import Slider from '#react-native-community/slider';
import CountDown from 'react-native-countdown-component';
import abacatezinImg from '../assets/abacatezinin.png';
import botaoStop from '../assets/botaoStop.png';
import botaoPlay from '../assets/botaoPlay.png';
export function Timer(){
const [range, setRange] = useState('0');
const [sliding, setSliding] = useState('Inactive');
const [isSecureEntry,setIsSecureEntry]=useState(true);
const navigation = useNavigation<any>();
function handleQuit(){
navigation.navigate('Quit');
}
if(isSecureEntry){
return(
<SafeAreaView style={styles.container}>
<Text style={styles.texto}>{range}</Text>
<View style={styles.container2}>
<Slider
style={styles.slider}
minimumValue={0}
maximumValue={60}
minimumTrackTintColor='#7E9F70'
maximumTrackTintColor='#A7C99A'
thumbImage={abacatezinImg}
value={30}
onValueChange={value => setRange(parseInt(value) + ':00')}
onSlidingStart={() => setSliding('Sliding')}
onSlidingComplete={() => setSliding('Inactive')}
step={5}
/>
<TouchableOpacity onPress={() =>{
setIsSecureEntry((prev)=> !prev)
}}>
<Image source={botaoPlay} style={styles.bPlay}/>
</TouchableOpacity>
</View>
</SafeAreaView>
);
}
else{
return(
<SafeAreaView style={styles.container}>
<Text style={styles.texto}>{range}</Text>
<View style={styles.container3}>
<TouchableOpacity onPress={handleQuit}>
<Image source={botaoStop} style={styles.bStop}/>
</TouchableOpacity>
</View>
</SafeAreaView>
);
}
}
const styles = StyleSheet.create({
container:{
flex: 1,
alignItems: 'center',
justifyContent: 'flex-start',
},
container2:{
backgroundColor: '#E4F0E2',
alignItems: 'center',
justifyContent: 'space-between',
flexDirection: 'row',
borderRadius: 100,
width: 327,
height: 66,
paddingHorizontal: 19,
marginTop: 20,
},
container3:{
alignItems: 'center',
justifyContent:'space-between',
marginTop: 20,
},
slider:{
width: 209,
height: 50,
transform: [{scaleY: 4}]
},
bPlay:{
width: 50,
height: 50,
},
bStop:{
width: 66,
height: 66,
},
texto:{
fontWeight: '300',
fontSize: 58,
lineHeight: 87,
letterSpacing: 0.03,
color: '#1B3810',
},
})
If anyone has any idea how to make it Id appreciate the help
Hooks(using useEffect) to countdown using setInterval in react - native:
const [timerCount, setTimer] = useState(60)
useEffect(() => {
let interval = setInterval(() => {
setTimer(lastTimerCount => {
if (lastTimerCount == 0) {
//your redirection to Quit screen
} else {
lastTimerCount <= 1 && clearInterval(interval)
return lastTimerCount - 1
}
})
}, 1000) //each count lasts for a second
//cleanup the interval on complete
return () => clearInterval(interval)
}, []);
use the state variable timerCount as:
<Text>{timerCount}</Text>

Render Error : Text strings must be rendered within a <Text> Component

I am developing a PDF viewer app.
Problem: I am displaying all the PDF's using Flatlist that is stored in a Firebase database. I am using react-native expo. When I open the application in a browser with expo it works. But when I run it on my phone it shows me an error as given below.
Error: Render Error : Text strings must be rendered within a <Text> Component
import React,{useEffect, useState} from "react";
import { FlatList, Text, StyleSheet, TouchableOpacity, View} from
"react-native";
import { config } from "../firebaseconfig";
import { getDatabase, ref ,onValue } from "firebase/database";
import { initializeApp } from "firebase/app";
const app = initializeApp(config);
function Books({navigation}) {
const [value ,setValue] = useState([]);
function readFunction() {
const db = getDatabase(app);
const reference = ref(db, "Books");
onValue(reference, (snapshot) => {
var main = [];
snapshot.forEach((childSnapshot) => {
const childKey = childSnapshot.key;
const childData = childSnapshot.val();
main.push({
title: childKey,
key:childData
});
});
setValue(main);
})
}
useEffect(() => {
readFunction()
},[]);
function renderItem({item}){
const path = item.key;
return (
<View style={styles.container}>
<View style={styles.square}>
<Text style={styles.h1}>{item.title}</Text>
<TouchableOpacity style={styles.button} onPress={() => navigation.navigate('Document', {path})}>Read</TouchableOpacity>
</View>
</View>
)
};
return (
<FlatList
data={value}
renderItem={renderItem}
keyExtractor={item => item.key}
/>
)
}
const styles = StyleSheet.create({
container:{
display: 'flex',
paddingLeft: '30px',
paddingRight:'30px',
paddingTop:'20px',
paddingBottom:'10px'
},
square:{
backgroundColor: 'white',
borderRadius: 4,
padding: '30px',
shadowColor: 'black',
shadowRadius: 10,
shadowOpacity: 1,
},
h1:{
textAlign: 'left',
fontFamily: 'Merriweather',
fontSize: 30,
},
p: {
textAlign: 'justify',
fontFamily: 'Open Sans',
fontSize: 15,
color: '#C8C8C8',
lineHeight: 18,
},
button: {
backgroundColor: '#3EDD84',
color: 'white',
width: '90px',
borderRadius: 3,
textAlign: 'center',
display: 'flex',
marginTop: '15px',
marginRight: '70px',
lineHeight:30,
fontSize: 25,
fontFamily: 'merriweather',
}
});
export default Books;
Try Doing this same
<View style={styles.container}>
<View style={styles.square}>
<Text style={styles.h1}>{item.title}</Text>
<TouchableOpacity style={styles.button} onPress={() => navigation.navigate('Document', {path})}>
<Text>Read</Text>
</TouchableOpacity>
</View>
You can't add Text inside TouchableOpacity component
Do this:
<TouchableOpacity style={styles.button} onPress={() => navigation.navigate('Document', {path})}>
<Text>Read</Text>
</TouchableOpacity>
I think the word Read between the TouchableOpacity tags should be within Text tags.

how to make background blur when modal open ups in reactnative

import React from 'react'
import { View, StyleSheet, Text, TouchableOpacity, Modal } from 'react-native'
const ModalContent = ({ visiblity, toggleModal }) => {
return (
<Modal animationType='slide' transparent={true} visible={visiblity} onRequestClose={() => {
toggleModal()
}} >
<View style={styles.container}>
<TouchableOpacity>
<Text style={styles.textButton}>Edit</Text>
</TouchableOpacity>
<TouchableOpacity>
<Text style={styles.textButton}>Invite</Text>
</TouchableOpacity>
<TouchableOpacity>
<Text style={styles.textButton}>Delete</Text>
</TouchableOpacity>
</View>
</Modal>
)
}
const styles = StyleSheet.create({
container: {
backgroundColor: 'white',
borderTopRightRadius: 25,
borderTopLeftRadius: 25,
height: 150,
alignItems: 'center',
elevation: 10,
alignItems: 'flex-start',
justifyContent: 'space-around',
paddingLeft: 20,
marginTop: 420
},
textButton: {
fontSize: 13,
color: 'black',
}
})
export default ModalContent
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
import React from 'react'
import { View, StyleSheet, Text, TouchableOpacity, Modal } from 'react-native'
const ModalContent = ({ visiblity, toggleModal }) => {
return (
<Modal animationType='slide' transparent={true} visible={visiblity} onRequestClose={() => {
toggleModal()
}} >
<View style={styles.container}>
<TouchableOpacity>
<Text style={styles.textButton}>Edit</Text>
</TouchableOpacity>
<TouchableOpacity>
<Text style={styles.textButton}>Invite</Text>
</TouchableOpacity>
<TouchableOpacity>
<Text style={styles.textButton}>Delete</Text>
</TouchableOpacity>
</View>
</Modal>
)
}
const styles = StyleSheet.create({
container: {
backgroundColor: 'white',
borderTopRightRadius: 25,
borderTopLeftRadius: 25,
height: 150,
alignItems: 'center',
elevation: 10,
alignItems: 'flex-start',
justifyContent: 'space-around',
paddingLeft: 20,
marginTop: 420
},
textButton: {
fontSize: 13,
color: 'black',
}
})
export default ModalContent
just simply adding backgroundcolor with opacity>>>>
backgroundColor: rgba(255, 0, 0, 0.2);
because in modal there is view contains view so if you give background color to that conatining view it will added blacky effect
In case you are using expo use
import { BlurView } from 'expo-blur';
When I added a blurView to my project, I browsed around for some third party libs and ended up with adding react-native-unimodules.
https://www.npmjs.com/package/#react-native-community/blur
you can use blurview so you can trigger blur when the bottomsheet opens or else make it normal
.
.
.
.
const [opensheet,setopensheet]=useState(false)
const [blur,setblur]=useState(0)
const ViewRef=useRef()
useEffect(
()=>
{
const changeBlur=()=>
{
if(opensheet)
setblur(25)
else
setblur(0)
}
changeBlur()
},
[opensheet]
)
.
.
.
return
(
<BlurView
ref={ViewRef}
blurAmount={blur}
>
.
.
.
)
--here opensheet is state of your modal which is defined by bool open/true and close/false
you have multiple way to solve this
one is using this library
https://github.com/Kureev/react-native-blur
one is with image with opacity blurradius
<Image
style={{opacity:0.8}
resizeMode='cover'
source={path}
blurRadius={1}
/>
another approach would to drop shadow with transparent background
i would go with first option becuase i already tried it

flat list error on fetching next page data

I am using redux to get the data from flatlist, in render item function i can see the data is rendering after fetching the page record it throw error
Invariant violation : tried to get frame out of range index 0
in debug statement in renderitem i can see the data is populated and it is printing the data in console. Below is my code
import React, { Component } from 'react'
import { FlatList, StyleSheet, View, Text,Image,ActivityIndicator,
Picker,TouchableOpacity,SectionList,DrawerLayoutAndroid,Alert,
TouchableHighlight,Button} from 'react-native'
import NumericInput from 'react-native-numeric-input'
import {connect} from 'react-redux';
import AlldataJson from './../Data/AllProduct.json'
import {
createDrawerNavigator,
createStackNavigator,
createAppContainer,
} from 'react-navigation';
const mapStateToProps = (state) =>{
// console.log('I am in mapstate to props '+ JSON.stringify(state));
return {
datasource:state.datasource,
isLoading:state.isLoading,
switchValue: state.switchValue,
page:state.page,
rerender:state.rerender,
isFetching: state.isFetching,
search:state.search,
LastSelectedItem:state.LastSelectedItem,
ItemSelected:state.ItemSelected,
setdrawerstate:state.setdrawerstate
}
};
const mapDispatchToProps=(dispatch)=>{
// console.log('i am ni map dispatch to props')
return {
quantitychange:(prodindex, changevalue)=>dispatch({type:"CHANGE_QTY",
index:prodindex,
value:changevalue}),
selectvaluechange:(index,itemvalue,itemindex)=>dispatch({type:"CHANGE_WEIGHT",
index:index,
itemvalue:itemvalue,
itemindex:itemindex}),
ToogleDrawerState:(newState)=>dispatch({type:'TOOGLE_DRAWER',newState:newState}),
taggleSwitch:(value,ind)=>dispatch({type:'TOOGLE_SWITCH',value:value,ind:ind}),
fetchAllData:(AlldataJson)=>dispatch({type:'ALL_DATA',AlldataJson:AlldataJson})
};
};
class DashBoard extends Component {
constructor(props) {
super(props)
console.log('i am in constructor')
console.log('the value getting as props is '+JSON.stringify(props));
// this.selectvaluechange=this.selectvaluechange.bind(this);
// this._opendrawer = this._opendrawer.bind(this);
} //constructor
packageList = (index) =>{
// console.log('i am in package list'+index)
return( this.props.datasource[index].pack.map( (x,j) => {
return( <Picker.Item label={x.Weight} key={j} value={x.packId}/>)}));
}
// Verdana 20
renderItem = ({ item,index }) => {
// console.log('i am in render item index is '+index+' item vale is '+JSON.stringify(item));
return(
<View style={{
flex: 1, flexDirection: 'row', marginBottom: 3,
paddingBottom: 10, paddingTop:10, paddingLeft: 10, backgroundColor: 'white', height: '25%'
}}>
<View style={{ width: '30%' }}>
<Image style={{ resizeMode: 'contain', height: '100%',width:'100%' }}
source={{ uri: this.props.datasource[index].imageUrl }} />
</View>
<View style={{ alignContent: 'center', paddingLeft: 40, width: '65%' }}>
<Text style={{
fontSize: 20, color: 'black', fontWeight: 'bold',
fontFamily: 'Verdana'
}}>
{item.Heading}</Text>
<Text style={{
fontSize: 12, paddingTop: 10, fontFamily: 'Verdana',
color: 'black', fontWeight: 'bold'
}}>{item.Details}</Text>
<View style={{ flex: 1, flexDirection: 'row', paddingTop: 15 }}>
<Text style={{ width: 40, height: 30, fontFamily: 'Verdana', fontWeight: 'bold' }}>Qty :</Text>
<NumericInput
totalHeight={30}
totalWidth={80}
minValue={0}
value={this.props.datasource[index].Qty}
onChange={(value) => this.props.quantitychange(index, value)} />
<Picker
style={{ marginLeft: 10, width: '45%', height: 40, fontFamily: 'Verdana', fontWeight: 'bold' }}
mode="dropdown"
selectedValue={this.props.datasource[index].packselectedValue}
onValueChange={(itemValue, itemIndex) => this.props.selectvaluechange(index, itemValue, itemIndex)}>
{this.packageList(index)}
</Picker>
</View>
<View >
<Text style={{ fontFamily: 'Verdana', fontWeight: 'bold' }}>Price : {this.props.datasource[index].
pack[this.props.datasource[index].packselectedValue].Price}
<Text style={{ fontFamily: 'Verdana', fontWeight: 'bold' }}> Amount : {this.props.datasource[index].
pack[this.pack.datasource[index].packselectedValue].Price *
this.props.datasource[index].Qty}
</Text>
</Text>
</View>
</View>
</View>
)
}
renderSeperator=()=>{
console.log('I am renderseperator the data ')
return(
<View style={{height:1,width:'100%',backgroundColor:'black'}}/>
)
}
onRefresh=()=>{
console.log('I am refreshing the data '+this.props)
// this.setState({isFetching:false})
}
componentDidMount() {
console.log('i am in component didmount ');
const url='./../Data/AllProduct.json'
// ./../Data/AllProduct.json'
fetch(url)
.then((response) => response.json())
.then((responsejson => {
console.log('i am in response json')
fetchAllData(responsejson)}))
//this.setState({ datasource: responsejson })})
.catch((error) => {
console.log('error in fetching the data bhasker')
this.props.fetchAllData(AlldataJson);
console.log('i am after fetchalldata function'+this.props)
})
this.props.navigation.setParams({ opendrawer: this._opendrawer});
}
// data={this.state.page===1?this.state.datasource:[this.state.datasource]}
render() {
// console.log('I am in render '+JSON.stringify(this.props.datasource));
return (
this.props.isLoading ?
<View style={{ flex: 1, justifyContent: 'center', alignContent: 'center' }}>
<ActivityIndicator size='large' color='#330066' animating />
</View> : <View>
<FlatList data={this.props.datasource}
renderItem={(item,index)=>this.renderItem(item,index)}
keyExtractor={item=>item.Id}
debug='yes'/>
</View>
)
}
}
export default connect(mapStateToProps,mapDispatchToProps)(DashBoard);
/* Reducer is */
import * as types from '../Action/ActionType'
import { objectExpression } from '#babel/types';
import Allproduct from './../Data/AllProduct';
const initialstate={
datasource: [],
isLoading:false,
switchValue: true,
page:1,
rerender:true ,
isFetching: false,
search:"" ,
LastSelectedItem:{Item:"",qty:"",weight:""},
ItemSelected:0,
setdrawerstate:true
}
const reducer = (state = initialstate, action) => {
// console.log('i am in reducer '+JSON.stringify(action));
switch (action.type) {
case "CHANGE_QTY":
break;
case "CHANGE_WEIGHT":
break;
case "TOOGLE_DRAWER":
break;
case "TOOGLE_SWITCH":
break;
case "ALL_DATA":
console.log('i am in all data') ;
return {...state,
datasource:action.AlldataJson};
default:
return state;
}
}
export default reducer;
/* All product json is */
[{"Id":"1","Heading":"Ashirvad","Details": "ashirvad Atta - Whole Wheet 10k Pouch",
"imageUrl": "https://www.aashirvaad.com/images/packet-2-right.png", "Qty": 0,
"pack": [{"packId":0,"Weight": "1kg","Price": 25},
{"packId":1,"Weight": "2kg","Price": 50},
{"packId":2,"Weight": "5kg","Price": 125},
{"packId":3,"Weight": "10kg","Price": 250}],
"packselectedValue":0,"isselected": false},
{"Id":"2","Heading": "Tata Salt","Details": "Tata Salt Iodised Salt 1kg Product",
"imageUrl": "http://tatasalt.com/public/front_assets/images/tab-product-img1.png",
"Qty": 0,
"pack": [{"packId":0,"Weight": "1kg","Price": 9.5},{"packId":1,"Weight": "2kg","Price": 19}, {"packId":2,"Weight": "5kg","Price": 47 },
{"packId":3,"Weight": "10kg","Price": 92}],"packselectedValue":0,"isselected": false}]
This is the error i am getting
It occurs because you have debug='yes' for the FlatList, and its data is initially an empty array. To remove the error, either of these should work:
remove the debug prop
add some dummy element to the initial data
render some other component (like a View) if the data array doesn't have any elements
Btw the function parameters/arguments in this line of FlatList
renderItem={(item,index)=>this.renderItem(item,index)}
should have curly braces ({})
renderItem={({item,index})=>this.renderItem({item,index})}
Or better yet, just change it to renderItem={this.renderItem}
Please accept this answer if it solved the problem. Thanks :)
Thanks Amrut Prabha for the help
the problem is in the below code.
<Text style={{ fontFamily: 'Verdana', fontWeight: 'bold' }}> Amount : {this.props.datasource[index].
pack[this.pack.datasource[index].packselectedValue].Price *
this.props.datasource[index].Qty}
pack[this.pack.datasource[index].packselectedValue.price is wrong..
pack[this.props.datasource[index].packselectedValue.price is correct.
i fixed the issue it solve the issue.

ScrollView steps over parent element while no flex but can not be seen with flex

I'm currently doing an example of a Model View with a label and a ScrollView below it. However, in the ScrollView's style when I set with no flex it goes over the parent element.
https://i.imgur.com/VGZ6vll.png
While if I set flex: 1 to the ScrollView style, the content does not show on the screen.
https://i.imgur.com/9e00ydF.png
Here is my code:
App.js:
import React, { Component } from "react";
import { Text, TouchableOpacity, View } from "react-native";
import Modal from "react-native-modal";
import ModalContent from './src/ModalContent';
export default class ModalTester extends Component {
state = {
isModalVisible: false
};
_toggleModal = () =>
this.setState({ isModalVisible: !this.state.isModalVisible });
render() {
return (
<View style={{ flex: 1 }}>
<TouchableOpacity onPress={this._toggleModal}>
<Text>Show Modal</Text>
</TouchableOpacity>
<Modal
isVisible={this.state.isModalVisible}
onBackdropPress={() => this.setState({ isModalVisible: false })}
>
<View style={styles.modalStyle}>
<ModalContent />
</View>
</Modal>
</View>
);
}
}
const styles = {
modalStyle: {
flex: 1,
marginTop: 20,
marginBottom: 20,
marginLeft: 10,
marginRight: 10,
backgroundColor: "#fff",
}
}
ModalContent.js:
import React from 'react';
import { View, Text, ScrollView } from 'react-native';
import InfoBox from './InfoBox'
export default () => {
return (
<View styles={styles.containerStyle}>
<Text style={styles.headerStyle}>TRIP INFO</Text>
<ScrollView style={styles.scrollViewStyle}>
<InfoBox boxHeight={100} />
<InfoBox boxHeight={200} />
<InfoBox boxHeight={400} />
</ScrollView>
</View>
);
}
const styles = {
containerStyle: {
flex: 1,
marginTop: 20,
marginBottom: 20,
marginLeft: 10,
marginRight: 10,
backgroundColor: "#fff",
},
headerStyle: {
fontSize: 35,
fontFamily: 'OpenSans',
fontWeight: 'bold',
color: '#be5bc2',
marginTop: 10,
marginLeft: 10,
},
scrollViewStyle: {
marginTop: 10,
}
}
InfoBox.js:
import React from 'react';
import { View, Text } from 'react-native';
export default ({boxHeight}) => {
setContainerStyle = function(setHeight) {
return ({
borderWidth: 1,
borderRadius: 4,
borderColor: "#000",
height: setHeight,
marginTop: 25,
marginLeft: 20,
marginRight: 20,
});
}
return (
<View style={this.setContainerStyle(boxHeight)}>
<Text>Hello</Text>
</View>
);
};
I have the same issue and change style for contentContainerStyle in ScrollView and works for me.
It would look like this:
<ScrollView contentContainerStyle={{ marginTop: 10 }} />