I am getting maximum depth exceeded while running react native code - reactjs

import { StyleSheet, Text, View, ImageBackground, SafeAreaView } from 'react-native';
import react, {useState} from 'react';
import InputComponent from './sharedComponent/InputComponent';
import ButtonComponent from './sharedComponent/ButtonComponent';
export default function App() {
const[text, setText] = useState('');
const[todoList, setToDoList] = useState([]);
return (
<ImageBackground
source={require('./assets/todoimages.png')}
style={{width: '100%', height: '100%'}}
>
<SafeAreaView>
<View style={styles.container}>
<InputComponent onchangeValue={setText}
/>
<ButtonComponent
addItem={setToDoList}
itemToAdd={text}
/>
</View>
<View>
{todoList.length > 0 && todoList.map((value) => <Text>{value}</Text>)}
</View>
</SafeAreaView>
</ImageBackground>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: 'baseline',
justifyContent: 'center',
paddingBottom:'10%'
},
});
I am getting the error :
Error: Maximum update depth exceeded. This can happen when a component repeatedly calls setState inside componentWillUpdate or componentDidUpdate. React limits the number of nested updates to prevent infinite loops.
can anyone tell me why I am getting the error and what is the solution for that?
below is the button component:
import {View,Button, StyleSheet} from 'react-native';
const ButtonComponent = (props) =>{
return(
<View style={styles.container}>
<View style={styles.buttonContainer}>
<Button
onPress={props.addItem(prevArray=> [...prevArray, props.itemToAdd])}
title="ADD"
/>
</View>
</View>
)
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
},
buttonContainer: {
margin: 20
},
})
export default ButtonComponent;
below is the input component:
import { Text, TextInput, View } from 'react-native';
const InputComponent = (props)=>{
return(
<TextInput
style={{height: 40, backgroundColor:'white'}}
placeholder="add the item in to do list"
onChangeText={newText => props.onchangeValue(newText)}
/>
)
}
export default InputComponent;

You must use arrow-functions in the onPress method of your buttonComponent like this:
onPress={()=>props.addItem(...)}

Related

cannot read property 'map' of undefined react native

image errors
The error Cannot read property 'map' of undefined' is thrown when the map function in the Product component is executed.
I'm following the react Native tutorial, and I keep running into an issue when passing the value from the state of one component into another component.
I'm following the react Native tutorial, and I keep running into an issue when passing the value from the state of one component into another component.
i used axios to get the data
ProductScreen
import React, {useEffect, useState} from 'react';
import {View} from 'react-native';
import MenuProduct from '../components/Product/MenuProduct';
import MainHeader from '../components/Header/MainHeader';
import {POPULAR, Top_Sell} from '../data';
import ProductItem from '../components/Product/ProductItem';
import instance from '../routes/instance';
const ProductScreen = () => {
const [product, setProduct] = useState([]);
useEffect(() => {
const fetchData = async () => {
const data = await instance('/api/products', {
method: 'GET',
});
setProduct(data);
};
fetchData();
}, []);
return (
<View style={{flex: 1}}>
<MainHeader />
<MenuProduct list={Top_Sell} />
<ProductItem list={product} />
</View>
);
};
export default ProductScreen;
ProductItem
import React from 'react';
import ProductCard from './ProductCard';
const ProductItem = ({product}) => {
return (
<>
{product.map((item, index) => {
return (
<ProductCard
id={item._id}
image={item.image}
title={item.title}
price={item.price}
item={item}
key={index}
/>
);
})}
</>
);
};
export default ProductItem;
ProductCard
import React from 'react';
import {Image, ScrollView, Text, TouchableOpacity, View} from 'react-native';
import {colors, sizes, spacing} from '../../constants/theme';
import AddItem from '../../utils/AddItem';
const CardHeight = 220;
const ProductCard = ({props}) => {
return (
<ScrollView>
return (
<View
style={{
marginLeft: spacing.l,
marginBottom: spacing.l,
marginRight: spacing.l,
}}>
<View>
<View
style={{
backgroundColor: colors.white,
borderRadius: sizes.radius,
shadowColor: colors.black,
shadowRadius: 4,
shadowOpacity: 0.1,
shadowOffset: {width: 0, height: 2},
}}>
<TouchableOpacity
style={{
borderRadius: sizes.radius,
overflow: 'hidden',
flexDirection: 'row',
}}>
<Image
style={{
borderRadius: sizes.radius,
width: 160,
height: CardHeight - 60,
resizeMode: 'cover',
}}
source={props.image}
/>
<View style={{marginTop: spacing.l}}>
<View style={{marginLeft: spacing.l, marginBottom: spacing.s}}>
<Text style={{fontSize: 16, color: '#FA4A0C'}}>
{props.title}
</Text>
</View>
<View style={{marginLeft: spacing.l}}>
<Text style={{fontSize: 14, color: '#8b8989'}}>
{props.price}
</Text>
</View>
<TouchableOpacity style={{marginLeft: 130}}>
<AddItem />
</TouchableOpacity>
</View>
</TouchableOpacity>
</View>
</View>
</View>
); })
</ScrollView>
);
};
export default ProductCard;
I have tried several ways on stackoverflow but I can't figure it out
It should be list in ProductItem component and use list.map because when you sending prop in ProductItem you are sending list
import React from 'react';
import ProductCard from './ProductCard';
const ProductItem = ({list}) => {
return (
<>
{list.length > 0 && list.map((item, index) => {
return (
<ProductCard
id={item._id}
image={item.image}
title={item.title}
price={item.price}
item={item}
key={index}
/>
);
})}
</>
);
};
export default ProductItem;
Check the below syntax for passing data from parent to child component.
<Child parentToChild={data}/>
Here, we are passing the data in the child component as data.
data is the data we have to pass, and parentToChild is the prop's name.
Next, it's time to capture the data in the child component. And it's very simple.
Here, there can be two cases.
Case 1: If you are using a functional component, simply catch the parentToChild in the parameters.
import React from 'react'
export default function Child({parentToChild}) {
return (
<div>
{parentToChild}
</div>
)
}
Case 2: If you have a class component, then just use this.props.parentToChild.
import React, { Component } from 'react'
export default class Child extends Component {
render() {
return (
<div>
{this.props.parentToChild}
</div>
)
}
}

in react native flatlist render function.. i'm componenting out a textinput and I am passing value through state props but onchange never fires

The text which is set to numerical never changes and the log never appears. This is so basic and weird that I can't get it to work.
const SetInput = props => {
return(
<View>
<TextInput
style={styles.textInput}
keyboardType='numeric'
onChange={props.handleSets}
value={props.value}
name={props.name}
maxLength={10} //setting limit of input
/>
</View>
)
};
heres the main component.... with setInput component and handleSets(); What happens is the number 4 initial state value is in the input but I can't change it and onChange never logs anything.
const FavoritesScreen = props => {
const favorites = useSelector(state => state.favorites.favoritedExercises);
const [sets, setSets] = useState('4');
const dispatch = useDispatch();
const handleSets = (e) => {
setSets(e.target.value)
console.log('sets handled')
}
const WorkoutRenderHandler = (favorites) => {
return(
<SafeAreaView>
<View style={styles.container}>
<View style={styles.workoutItem}>
<View style={styles.flexthing}>
<Text numberOfLines={1} style={styles.name}> {favorites.item.name}</Text>
{/* <Image source={{uri: favorites.item.gifUrl}} style={{width: 40, height: 40}}/> */}
<Text style={styles.equipment}>{favorites.item.equipment}</Text>
<SetInput onChange={handleSets} value={sets}/>
</View>
</View>
</View>
</SafeAreaView>
)
};
return (
<ReturnedWorkoutList data={favorites} renderItem={WorkoutRenderHandler} style={styles.screen} extaData={sets}/>
};
Try this
import React, { useState, useEffect } from "react";
import { Text, View, StyleSheet, TextInput, } from 'react-native';
import Constants from 'expo-constants';
// You can import from local files
import AssetExample from './components/AssetExample';
// or any pure javascript modules available in npm
import { Card } from 'react-native-paper';
export default function App() {
const [formData, setData] = useState({});
const handleSets = (e) => {
setData({ ...formData, eventtitle: e })
console.log('sets handled')
}
return (
<View style={styles.container}>
<TextInput placeholder="WRITE HERE" onChangeText={value => handleSets(value)}/>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
paddingTop: Constants.statusBarHeight,
backgroundColor: '#ecf0f1',
padding: 8,
}
});
DEMO: https://snack.expo.dev/#g1sm0/ryan-hartley

React Native - React Navigation Cannot use Hooks in DrawerContent

I am developing an e-commerce application using React Native and I am trying to use useState in the drawerContent and it tells me this
Error: Invalid hook call. Hooks can only be called inside of the body
of a function component. This could happen for one of the following
reasons:
You might have mismatching versions of React and the renderer (such as React DOM)
You might be breaking the Rules of Hooks
You might have more than one copy of React in the same app
Thank you in advance for your answers.
Here's the code
import React, { useState } from 'react'
import { View, Text, TouchableOpacity, FlatList, StyleSheet, StatusBar } from 'react-native'
import IonIcons from "react-native-vector-icons/Ionicons"
import { categories } from '../../../services/DataTest'
import DrawerSearch from './DrawerSearch'
import DrawerItem from './DrawerItem'
export default function DrawerContent (props) {
const [search, setSearch] = useState("");
return (
<View>
<TouchableOpacity
style={styles.customDrawerTouch}
>
<View style={styles.backButtonRow}>
<IonIcons
name="ios-arrow-back"
size={25}
style={styles.customDrawerIcon}
color="#666666"
/>
<Text style={{ color: '#666666' }}>Back to Components</Text>
</View>
</TouchableOpacity>
<DrawerSearch value={search} setValue={setSearch}/>
<FlatList
data={categories}
keyExtractor={(item, index) => index.toString()}
renderItem={DrawerItem}
/>
</View>
);
}
const styles = StyleSheet.create({
customDrawerTouch: {
marginTop: StatusBar.currentHeight,
paddingLeft: 13,
paddingTop: 15,
},
customDrawerIcon: {
paddingRight: 10
},
backButtonRow: {
flexDirection: 'row',
alignItems: 'center',
paddingBottom: 17,
paddingLeft: 3,
borderBottomColor: '#F0F0F0',
borderBottomWidth: 1,
},
});
I'm using this component here
import * as React from 'react';
import { View, StyleSheet, StatusBar } from 'react-native';
import { createDrawerNavigator } from '#react-navigation/drawer';
import HeaderCategorie from '../../components/categories/index/HeaderCategorie';
import SearchBar from '../../components/home/index/SearchBar';
import DrawerContent from '../../components/categories/index/DrawerContent';
const Drawer = createDrawerNavigator();
function CategoriesScreen({ navigation }) {
return (
<View style={styles.container}>
<HeaderCategorie navigation={navigation}/>
<View style={styles.headerSearch}>
<SearchBar />
</View>
</View>
)
}
export default function Categories() {
return (
<Drawer.Navigator initialRouteName="Categories"
drawerContent={DrawerContent}
screenOptions={{headerShown:false}}
>
<Drawer.Screen name="Categories" component={CategoriesScreen} />
</Drawer.Navigator>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: "flex-start",
alignItems: "center",
marginTop: StatusBar.currentHeight,
},
headerSearch: {
marginVertical:10
},
headerSearchText: {
fontWeight:"bold",
fontSize:35,
marginLeft:20,
marginVertical:15,
}
});
Reason: By using drawerContent={DrawerContent}, you are actually passing the reference of the DrawerContent function, which ends up breaking rules of hooks.
So to resolve this, change the following line:
<Drawer.Navigator initialRouteName="Categories"
drawerContent={DrawerContent}
screenOptions={{headerShown:false}}
>
to this
<Drawer.Navigator initialRouteName="Categories"
drawerContent={(props)=> <DrawerContent {...props}/>} // here
screenOptions={{headerShown:false}}
>
demo snack

invarient voilation: resources are not useable as native method argument

i am new here and stuck because of this error. please help me to solve this error.
import React from "react";
import { View, Image, StyleSheet, Text, TouchableOpacity } from "react-native";
function ListItem({ image, title, subtitle }) {
return (
<TouchableOpacity>
<View style={styles.container}>
{image && <Image style={styles.img} source={image} />}
<View>
<Text>{title}</Text>
<Text>{subtitle}</Text>
</View>
</View>
</TouchableOpacity>
);
}
const styles = StyleSheet.create({
container: {
flexDirection: "row"
},
img: {
width: 70,
height: 70,
borderRadius: 35
}
});
export default ListItem;
and invoke it in other component with passing arguments
import * as React from "react";
import Icon from "./Components/Icon";
export default function App() {
return (
<SafeAreaView style={styles.screen}>
<ListItem
title="My title"
subtitle="subtitle"
imgComponent={<Icon name="email" />}
/>
</SafeAreaView>
);
}
and i am facing this error

use native base button with props

i want to create a reusable button component but i am having some issues. I get back undefined is not an onject evaluting '_nativebase.stylrsheetcreate'. I tried destructing the onPress and title but no luck. Can someone give a clear explanation on how to resolve this? thanks
import React from 'react';
import { View, Text, Button, StyleSheet } from 'native-base';
export const StyledButton = props => {
return (
<View style={styles.button}>
<Button
block
full
bordered
light
onPress={this.props.onPress}
>
<Text
style={{
color: '#FFFFFF',
}}
>
{this.props.title}
</Text>
{this.props.children}
</Button>
</View>
);
};
const styles = StyleSheet.create({
button: {
flex: 1,
padding: 10,
}
});
to Render
<StyledButton
title='Cancel'
onPress={this.somefunction}
/>
Remove this use props.someprop
import React from 'react';
import { StyleSheet } from 'react-native';
import { View, Text, Button } from 'native-base';
export const StyledButton = props => {
return (
<View style={styles.button}>
<Button block full bordered light onPress={props.onPress}>
<Text
style={{
color: '#FFFFFF',
}}>
{props.title}
</Text>
{props.children}
</Button>
</View>
);
};
const styles = StyleSheet.create({
button: {
flex: 1,
padding: 10,
}
});

Resources