React Native Elements Checkbox SetState is not a function - react-native

Have implemented a screen that uses checkboxes.
Following the example from React Native Checkbox
On clicking a checkbox, receive the following error:
TypeError: _this.setState is not a function. (In '_this.setState({
checked: !_this.state.checked
})', '_this.setState' is undefined)
Below is my code:
import * as React from 'react';
import {Dimensions, StyleSheet, View} from 'react-native';
import {Button, Card, CheckBox} from 'react-native-elements';
function MyScreen({navigation}) {
return (
<View style={styles.view}>
<View style={styles.panel}>
<Card containerStyle={styles.card} title="My Checkboxes">
<CheckBox
title="My Checkbox"
checked={this.state.checked}
onPress={() => this.setState({checked: !this.state.checked})}
/>
</Card>
<Button
style={styles.button}
title="Done"
onPress={() => navigation.navigate('Home')}
/>
</View>
</View>
);
}
const styles = StyleSheet.create({
view: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
},
panel: {
width: Dimensions.get('window').width,
justifyContent: 'center',
alignItems: 'center',
position: 'absolute',
top: 0,
},
button: {
margin: 5,
width: 150,
height: 50,
},
card: {
width: Dimensions.get('window').width,
marginBottom: 20,
},
});
export default MyScreen;
I've tried searching here, and pretty much everywhere, and can't seem to find a solution.
Any assistance would be appreciated.

You are using a functional component.
Change it to a class component or use hooks inside this functional component.
Change your code as following
class component
import React, { Component } from 'react'
import {Dimensions, StyleSheet, View} from 'react-native';
import {Button, Card, CheckBox} from 'react-native-elements';
export default class App extends Component {
state={ checked: false };
render() {
return (
<View style={styles.view}>
<View style={styles.panel}>
<Card containerStyle={styles.card} title="My Checkboxes">
<CheckBox
title="My Checkbox"
checked={this.state.checked}
onPress={() => this.setState({checked: !this.state.checked})}
/>
</Card>
<Button
style={styles.button}
title="Done"
onPress={() => navigation.navigate('Home')}
/>
</View>
</View>
)
}
}
or functional component
import React, {useState} from 'react';
import {Dimensions, StyleSheet, View} from 'react-native';
import {Button, Card, CheckBox} from 'react-native-elements';
function MyScreen({navigation}) {
const [checked, toggleChecked] = useState(false);
return (
<View style={styles.view}>
<View style={styles.panel}>
<Card containerStyle={styles.card} title="My Checkboxes">
<CheckBox
title="My Checkbox"
checked={checked}
onPress={() => toggleChecked(!checked)}
/>
</Card>
<Button
style={styles.button}
title="Done"
onPress={() => navigation.navigate('Home')}
/>
</View>
</View>
);
}

If you are using your functional component as a child in another component, you can have use props instead.
function MyScreen({navigation, onChecked, checked}) {
return (
<View style={styles.view}>
<View style={styles.panel}>
<Card containerStyle={styles.card} title="My Checkboxes">
<CheckBox
title="My Checkbox"
checked={checked}
onPress={onChecked}
/>
</Card>
<Button
style={styles.button}
title="Done"
onPress={() => navigation.navigate('Home')}
/>
</View>
</View>
);
}
MyScreen.propTypes = {
checked: PropTypes.bool.isRequired,
onChecked: PropTypes.func.isRequired
};
export default MyScreen;
On the parent component the onChecked can look like:
onChecked =()=>{
...
this.setState({checked: !this.state.checked})
}
Also in the parent component, you can use MyScreen as:
<MyScreen
onCheck={this.onChecked}
checked={this.state.checked}
/>

Related

array values showing undefined in react native expo while working in web

The code is working in web version of react native but not in expo The array values are showing unefined but they are working fine in web version.Please tell me what is wrong here
import { View, Text, StyleSheet } from "react-native"
import React from "react"
import { FontAwesomeIcon } from "#fortawesome/react-native-fontawesome"
import { faEdit, faMinusSquare } from "#fortawesome/free-regular-svg-icons"
function List({ todoArr, handleModalOpen, removeItem }) {
console.log(todoArr)
return (
<>
{todoArr.map((item, index) => {
console.log(index)
return (
<View>
<Text key={item} style={styles.item}>{item}</Text>
<Text onPress={() => handleModalOpen(index, item)}>
<FontAwesomeIcon icon={faEdit} />
</Text>
<Text onPress={() => removeItem(index)}>
<FontAwesomeIcon icon={faMinusSquare} />
</Text>
</View>
)
})}
</>
)
}
const styles = StyleSheet.create({
item: {
fontSize: 20
},
})
export default List
import { ScrollView, StyleSheet, Text, View } from 'react-native';
import Buttons from './components/Add and Del Btn';
import EditModal from './components/EditModal';
import Heading from './components/Heading';
import Input from './components/Input';
import List from './components/List';
import Todo from './todo';
export default function App() {
let [indexNo , inpVal,updInpVal , todoArr,modalVisible ,setUpdInpVal , getInp, add, delAll, removeItem, editItem , handleModalClose , handleModalOpen] = Todo();
return (
<View style={styles.container}>
<EditModal modalVisible = {modalVisible} updInpVal={updInpVal} setUpdInpVal = {setUpdInpVal} editItem = {editItem} indexNo = {indexNo}/>
<View>
<Heading />
<View>
<Input getInp={getInp} inpVal={inpVal} />
<Buttons add={add} delAll={delAll} />
</View>
<View>
<List todoArr={todoArr} handleModalOpen={handleModalOpen} removeItem={removeItem} />
</View>
</View>
</View >
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
},
});

Balise <View> on react-native

i try to make an app on react-native for the first time and I have a problem.
I code a component who show a screen with some text and a button but they didn't shown on the app and I don't know why.
I code on snack.expo.dev, i'm new on this but i try to learn a lot about that informatic language.
import * as React from 'react';
import { StyleSheet, View, Text, Button } from 'react-native';
import { NavigationContainer } from '#react-navigation/native';
import { createNativeStackNavigator } from '#react-navigation/native-stack';
import { StartScreen } from "./routes/Start_page";
function HomeScreen() {
return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<Text>Home Screen</Text>
</View>
);
}
/*const StartScreen = () => {
return(
<View>
<Text>(Screen 1)</Text>
<Text>Welcome to My App</Text>
<Button
title="Start!"
onPress={() => {}}
>
</Button>
</View>
);
}*/
const DashboardScreen = () => {
return(
<View>
<Text>(Screen 2)</Text>
<Text>Dashboard</Text>
<Button
title="Back"
onPress={() => {}}
>
</Button>
</View>
);
}
const Stack = createNativeStackNavigator();
function App() {
return (
<NavigationContainer>
<Stack.Navigator initialRouteName={"Start"}>
<Stack.Screen name="Start" component={StartScreen} />
<Stack.Screen name="Home" component={HomeScreen} />
<Stack.Screen name="Dashboard" component={DashboardScreen} />
</Stack.Navigator>
</NavigationContainer>
);
}
export default App;
/*const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: "#fff",
alignItems: "center",
justifyContent: "center",
},
});*/
import * as React from 'react';
import { StyleSheet, View, Text, Button } from 'react-native';
const StartScreen = () => {
return(
<View>
<Text>(Screen 1)</Text>
<Text>Welcome to My App</Text>
<Button
title="Start!"
onPress={() => {}}
>
</Button>
</View>
);
}
I try to add more text to post xD
You just forgot to export the const StartScreen in the file ./routes/Start_page/index.tsx. It will be like this:
import * as React from 'react';
import { StyleSheet, View, Text, Button } from 'react-native';
export const StartScreen = () => {
return(
<View>
<Text>(Screen 1)</Text>
<Text>Welcome to My App</Text>
<Button
title="Start!"
onPress={() => {}}
>
</Button>
</View>
);
}

ReactNative send style as props to component

I am new to learning React Native and I would like to build a (ReactNaive & Expo) application with a good interface look, How can I build a component and send style{backgroundColor} as props then render the component on Home
home.js
import React from 'react'
import { View, Text , Image , ScrollView} from 'react-native';
import { FlatList } from 'react-native-gesture-handler';
import { COLORS, SIZES,FONTS} from '../styles/theme.js';
import Category from '../components/Category.js';
import CategorySlider from '../components/CategorySlider'
const Home = () => {
function renderHeader(){
return(
<View
style = {{
flexDirection: 'row' ,
marginTop: 40,
marginBottom: 10,
paddingHorizontal:SIZES.padding,
alignItems : 'center'
}}
>
<View style={{flex:1}}>
<Text >Hello , Wafa</Text>
</View>
{/* Nonfiction Button */}
</View>
)}
return (
<View
style ={{
flex: 1,
backgroundColor: COLORS.white
}}
>
{/* HEADER */}
{renderHeader()}
{/* Content */}
<View style={{height:130 , marginTop:SIZES.margin}}>
<ScrollView
horizontal={true}
showsHorizontalScrollIndicator={false}
>
<Category name='Balance' />
<Category name='Saving' style={COLORS.green} />
<Category name='Income' style={ COLORS.brown } />
<Category name='Loans' style={ COLORS.pink}/>
<Category name='Saving' style={ COLORS.pink}/>
<Category name='Saving' style={ COLORS.pink}/>
</ScrollView>
</View>
<CategorySlider/>
</View>
)
}
export default Home;
It is the component I want to render on home.js
Category.js
import React, { PureComponent } from 'react'
import { Text, View ,StyleSheet ,Image } from 'react-native'
import { backgroundColor } from 'react-native/Libraries/Components/View/ReactNativeStyleAttributes';
import { COLORS, SIZES,FONTS} from '../styles/theme.js';
export default class Category extends PureComponent {
render() {
return (
<View style={{marginLeft: SIZES.margin ,marginRight: SIZES.margin}}>
<View>
<View style={{
height: 60,
width: 60,
backgroundColor:COLORS.pink,
borderRadius: SIZES.radius,
}}>
<View />
<View>
<Image />
</View>
</View>
<Text
style={{textAlign:'center'}}
>
{this.props.name}</Text>
</View>
</View>
)
}
}
l made also File for Design system contains style I will repeat on the application.
theme.js:
import { Dimensions } from "react-native";
import { useFonts } from 'expo-font';
const { width, height } = Dimensions.get("window");
export const COLORS = {
green: "#68AB9F",
brown: "#c18e62",
pink: "#d99e96" ,
gray: "#383e42",
white: "#f5f7fc",
}
Here you're working on one with a Functional based component (home.js) and one with Class-based (Category.js). Standard is if first convert your Category component with functional then you can save that props to your Category component like:
import React, { useState } from 'react'
import { Text, View ,StyleSheet ,Image } from 'react-native'
import { backgroundColor } from 'react-native/Libraries/Components/View/ReactNativeStyleAttributes';
import { COLORS, SIZES,FONTS} from '../styles/theme.js';
const Category = (props) => {
const [backgroundColor, setBackgroundColor] = useState(props.style || null); //store your prop in state like this
const [name, setName] = useState(props.name || null);
return (
<View style={{marginLeft: SIZES.margin ,marginRight: SIZES.margin}}>
<View>
<View style={{
height: 60,
width: 60,
backgroundColor: backgroundColor,
borderRadius: SIZES.radius,
}}>
<View />
<View>
<Image />
</View>
</View>
<Text
style={{textAlign:'center'}}
>
{name}</Text>
</View>
</View>
)
}
export default Category;
Hope this works for you.
In your parent component take your style object in the wrapper of child component i.e.
function Parent(){
return (
<Child cssdata={{backgroundColor:'red',marginLeft:8}}/>
)
}
and in your child component take this data from props and applied to it
function Child(props){
return (
<View style={props.cssdata}></View>
)
}

Error : You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports

I got this error when trying to import and use another component that I have created in another file. And I got an error like this :
Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.
Check the render method of `Sidebar`.
This is my code to export component as default component in customDrawer.js which file is same directory:
const Sidebar = ({ isDarkTheme, setIsDarkTheme, ...props }) => {
const handlePress = () => {
props.navigation.dispatch(DrawerActions.closeDrawer());
props.navigation.navigate("Settings");
};
const { colors } = useTheme();
const toggleTheme = () => {
setIsDarkTheme();
};
// console.log('navi--?',props.navigation);
return (
<Container style={{ backgroundColor: colors.background }}>
<Header
style={{
backgroundColor: colors.background,
borderBottomWidth: 0,
marginTop: 70,
borderWidth: 0,
}}
>
<StatusBar barStyle="dark-content" backgroundColor="#ffffff" />
<Right>
<Button transparent>
<TouchableOpacity onPress={() => handlePress()}>
{/* <Ionicons name="ios-options" size={28} color={colors.icon} /> */}
</TouchableOpacity>
</Button>
</Right>
</Header>
<Content>
<DrawerContentScrollView {...props}>
<DrawerItemList {...props} />
</DrawerContentScrollView>
<TouchableOpacity>
<View
style={{
display: "flex",
flexDirection: "row",
alignItems: "center",
paddingRight: 20,
paddingLeft: 20,
paddingTop: 10,
}}
>
<Text style={{ flex: 1, color: colors.text }}>Dark Theme</Text>
<View>
<Switch onValueChange={toggleTheme} value={isDarkTheme} />
</View>
</View>
</TouchableOpacity>
</Content>
</Container>
);
};
const styles = StyleSheet.create({});
export default Sidebar;
And then, in my App.js I have import components like this :
import Sidebar from "./customDrawer";
All imports I use in customDrawer.js :
import {
DrawerContentScrollView,
DrawerItemList,
} from "#react-navigation/drawer";
import { Button, Container, Content, Header, Right } from "native-base";
import React, { useState } from "react";
//import { Ionicons } from "#expo/vector-icons";
import { StyleSheet, Text, View, Switch } from "react-native";
import { StatusBar } from "react-native";
import { TouchableOpacity } from "react-native";
import { DrawerActions } from "#react-navigation/native";
import { useTheme } from "#react-navigation/native";

How to fix Require cycle warning In React Expo

I'm getting this error.[ErrorImg][1]
This is Require cycles error but I can't find what is the reason.
I want to use ListItem component to View.js through component.js and I already use that like this import {ListItem } from '../components/';.
The result is good but there is this warning and I want to fix. Please help me.
Require cycle: Components.js->
import Button from './Button';
import Select from './Select';
import Icon from './Icon';
import Tabs from './Tabs';
import Product from './Product';
import Drawer from './Drawer';
import Header from './Header';
import Switch from './Switch';
import ListItem from './ListItem';
import HorizontalListItem from './HorizontalListItem';
export {
Button,
Select,
Icon,
Tabs,
Product,
Drawer,
Header,
Switch,
ListItem,
HorizontalListItem,
};```
View.js->
```const renderPatientsList = () => {
return(
<Block style={{ paddingHorizontal: theme.SIZES.BASE }}>
<ScrollView vertical={true} showsVerticalScrollIndicator={false} style={{marginBottom: theme.SIZES.BASE * 3}}>
<ListItem product={products[0]} horizontal />
<ListItem product={products[1]} horizontal />
<ListItem product={products[2]} horizontal />
</ScrollView>
</Block>
)
}```
ListItem.js -->
```import React from 'react';
import { withNavigation } from '#react-navigation/compat';
import { StyleSheet, Dimensions, Image, TouchableWithoutFeedback } from 'react-native';
import { Block, Text, theme } from 'galio-framework';
import { Icon } from '../components/';
import { LinearGradient } from 'expo-linear-gradient';
const { width } = Dimensions.get('screen');
const ListItem = props => {
const { navigation, product, horizontal, full, style, priceColor, imageStyle, time, unReaden, weekday } = props;
const imageStyles = [styles.image, full ? styles.fullImage : styles.horizontalImage, imageStyle];
return (
<Block row={horizontal} card flex style={[styles.product, styles.shadow, style]}>
<TouchableWithoutFeedback onPress={() => navigation.navigate('Product', { product: product })}>
<Block style={[styles.imageContainer, styles.shadow]}>
<Image source={{ uri: product.image }} style={imageStyles}/>
</Block>
</TouchableWithoutFeedback>
<TouchableWithoutFeedback onPress={() => navigation.navigate('Product', { product: product })}>
<Block flex={3}>
<Text size={16} style={styles.userName}>{product.title}</Text>
<Block flexDirection={'row'}>
<Icon name="photo" family="font-awesome" color={theme.COLORS.MUTED} size={theme.SIZES.BASE} style={styles.icons}> </Icon>
<Icon name="check" family="font-awesome" color={theme.COLORS.MUTED} size={theme.SIZES.BASE} style={styles.icons}> </Icon>
<Text size={16} muted={!priceColor} color={priceColor}>${product.price}</Text>
</Block>
</Block>
</TouchableWithoutFeedback>
<TouchableWithoutFeedback onPress={() => navigation.navigate('Product', { product: product })}>
<Block flex={1}>
<>
{(product.time) ? (
<Text size={12} style={styles.times} color={"#06D81E"}>{product.time}</Text>
) : (
<Text size={12} style={styles.times} color={"#000"}>{product.weekday}</Text>
)}
</>
<Block style={{borderRadius: 100, backgroundColor: "#06D81E", width: theme.SIZES.BASE * 1.2, height: theme.SIZES.BASE * 1.2, position: "absolute", right: theme.SIZES.BASE, bottom: theme.SIZES.BASE}}>
<Text size={12} center style={{justifyContent: 'center', alignItems: 'center'}} color={"#FFF"} fontWeight={"semiBold"}>{product.unReaden}</Text>
</Block>
</Block>
</TouchableWithoutFeedback>
</Block>
);
}```
[1]: https://i.stack.imgur.com/rDB6i.png
You are getting require cycle warning because you end up creating a loop ( require from Component.js in ListItem.js and require from ListItem.js in Component.js)
In ListItem.js,
import {Icon} from Icon.js
The general idea is to write the module in another file and import that module from there.
see this for a detailed explanation:
Require cycles are allowed, but can result in uninitialized values. Consider refactoring to remove the need for a cycle