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 - react-native

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";

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',
},
});

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>
)
}

Cannot read property 'navigation' of undefined Evaluating App.js Loading App.js

Looking to have button enter go into another screen:
need help with navigation screen.
I keep getting error:
Cannot read property 'navigation' of undefined
Evaluating App.js
Loading App.js
TypeError: Cannot read property 'navigation' of undefined
https://snack.expo.io/#ganiyat1/colorful-thrills
import * as React from 'react';
import { Text, View, StyleSheet, ImageBackground, Image, Button } from 'react-native';
import Constants from 'expo-constants';
import { StackNavigator} from 'react-navigation';
import Books from './components/Books';
// You can import from local files
// or any pure javascript modules available in npm
import { Card } from 'react-native-paper';
const Book = StackNavigator({
Books: { screen: Books },
});
const { navigate } = this.props.navigation;
export default function App() {
return (
<View style={styles.container}>
<View style={styles.topContainer}>
<Text style={styles.title}> Colorful Thrills
</Text >
</View>
<View style={styles.bottomContainer}></View>
<View style={styles.imageContainer}>
<Image
style={styles.image}
source={require('./assets/bookcover.png')}
/>
<Text style={styles.paragraph}>
{"\n"} BOOKWORMS, UNITE! {"\n"} {"\n"}
Suspense, Mystery and Thrillers by Authors of Color
</Text>
<Button
color='#ff914d'
title= 'ENTER'
onPress={() =>
navigate('Books')}
/>
</View>
</View>
);
}
In the above code snippet, I don't see a default Navigator being returned form the entry file, which is App.js by default in React Native.
I assume that you just started to learn React Native, so I will spare you all the minor details and walk you through the solution.
I refactored the App.js file to a into a new component file in /components/Home.js.
Added a default stack Navigator in App.js which has two screens, Home and Books.
Now you can access all the Navigation props in your Home and Books component, as it is being declared in the Navigator variable in App.js
Here is a live demo of your code on Expo.
//App.js
import * as React from 'react';
import { Text, View, StyleSheet, ImageBackground, Image, Button } from 'react-native';
import Constants from 'expo-constants';
import { StackNavigator} from 'react-navigation';
import Books from './components/Books';
import Home from './components/Home'
import { Card } from 'react-native-paper';
const Navigator = StackNavigator({
Books: { screen: Books },
Home:{screen:Home}
});
export default function App(props) {
return (
<Navigator />
);
}
//component/Books.js
import React, { useState } from 'react';
import { StyleSheet, SafeAreaView,Button } from 'react-native';
import MaterialTabs from 'react-native-material-tabs';
const Books = (props) => {
const {navigation} = props
const [selectedTab, setSelectedTab] = useState(0);
return (
<SafeAreaView style={styles.container}>
<MaterialTabs
items={['New Releases', 'All', 'BOM']}
selectedIndex={selectedTab}
onChange={setSelectedTab}
barColor="#1fbcd2"
indicatorColor="#ff914d"
activeTextColor="white"
/>
<Button
color='#ff914d'
title= 'Home'
onPress={() =>
navigation.navigate('Home')}
/>
</SafeAreaView>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
},
});
export default Books
//component/Home.js
import React from 'react'
import {View,Text,StyleSheet,Button,Image} from 'react-native'
const Home = (props) => {
const {navigation} = props
return (
<View style={styles.container}>
<View style={styles.topContainer}>
<Text style={styles.title}> Colorful Thrills
</Text >
</View>
<View style={styles.bottomContainer}></View>
<View style={styles.imageContainer}>
<Image
style={styles.image}
source={require('../assets/bookcover.png')}
/>
<Text style={styles.paragraph}>
{"\n"} BOOKWORMS, UNITE! {"\n"} {"\n"}
Suspense, Mystery and Thrillers by Authors of Color
</Text>
<Button
color='#ff914d'
title= 'ENTER'
onPress={() =>
navigation.navigate('Books')}
/>
</View>
</View>
)
}
export default Home
const styles = StyleSheet.create({
container: {
flex: 1,
flexDirection: 'column',
},
topContainer: {
flex: 1,
backgroundColor: '#ff914d',
},
bottomContainer: {
flex: 1,
backgroundColor: '#96d0e3',
},
imageContainer: {
position: 'absolute',
width: '100%',
height: '100%',
justifyContent: 'center',
alignItems: 'center',
},
image: {
width: 300,
},
title:{
margin: 24,
marginTop: 50,
fontSize: 40,
fontWeight: 'bold',
textAlign: 'center',
fontFamily: 'GillSans-Italic',
},
paragraph: {
margin: 24,
marginTop: 0,
fontSize: 20,
fontWeight: 'bold',
textAlign: 'center',
}
});

React Native Elements Checkbox SetState is not a function

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}
/>

React native layout misbehaving

I am trying to learn React native with Ignite. Been fighting with the layout.
Here is my main container render function:
render () {
return (
<View style={styles.mainContainer}>
<Image source={Images.background} style={styles.backgroundImage} resizeMode='stretch' />
<View style={[styles.container]}>
<View style={styles.section} >
{/* <Image source={Images.ready} />*/}
<Text style={styles.sectionText}>
Tap to randomly choose your training task. Slack off for 5
</Text>
</View>
<View style={styles.centered}>
<TouchableOpacity onPress={this._onPressButton}>
<Image source={Images.launch} style={styles.logo} />
</TouchableOpacity>
</View>
</View>
<View style={[styles.bottom]}>
<View >
<BottomBar />
</View>
</View>
</View>
)
}
In particular, the last sibling of the container has a view with a BottomBar component.The bottom style does this:
bottom: {
justifyContent: 'flex-end',
marginBottom: Metrics.baseMargin
}
the BottomBar component:
import React, { Component } from 'react'
// import PropTypes from 'prop-types';
import { View, Text, TouchableOpacity } from 'react-native'
import styles from './Styles/BottomBarStyle'
import Icon from 'react-native-vector-icons/FontAwesome'
export default class BottomBar extends Component {
// // Prop type warnings
// static propTypes = {
// someProperty: PropTypes.object,
// someSetting: PropTypes.bool.isRequired,
// }
//
// // Defaults for props
// static defaultProps = {
// someSetting: false
// }
render () {
console.tron.log('rendering my component')
console.tron.log('Bottom bar styles: \n',styles)
return (
<View style={[styles.iconsContainer, styles.debugGreen]}>
<TouchableOpacity style={[styles.icons,styles.debugYellow]} onPress={()=>{console.tron.log('rocket')}} >
<Icon style={styles.icons} name='rocket' size={40} color='white' />
</TouchableOpacity>
<TouchableOpacity style={styles.button} onPress={ ()=>{console.tron.log('send')} }>
<Icon style={styles.icons} name='send' size={40} color='white' />
</TouchableOpacity>
</View>
)
}
}
the styles associated with it:
import { StyleSheet } from 'react-native'
import DebugStyles from '../../Themes/DebugStyles'
import { Metrics } from '../../Themes/'
export default StyleSheet.create({
...DebugStyles,
iconsContainer: {
flex: 1,
flexDirection: 'row',
justifyContent: 'space-between',
height: 45,
borderRadius: 5,
marginHorizontal: Metrics.section,
marginVertical: Metrics.baseMargin
},
icons:{
height: 45
}
})
The issue I have, is that if I saw that bottomBar component for a Rounded button as such:
import React, { Component } from 'react'
import PropTypes from 'prop-types'
import { TouchableOpacity, Text } from 'react-native'
import styles from './Styles/RoundedButtonStyles'
import ExamplesRegistry from '../Services/ExamplesRegistry'
// Note that this file (App/Components/RoundedButton) needs to be
// imported in your app somewhere, otherwise your component won't be
// compiled and added to the examples dev screen.
// Ignore in coverage report
/* istanbul ignore next */
ExamplesRegistry.addComponentExample('Rounded Button', () =>
<RoundedButton
text='real buttons have curves'
onPress={() => window.alert('Rounded Button Pressed!')}
/>
)
console.tron.log('Rounded button style: ',styles)
export default class RoundedButton extends Component {
static propTypes = {
onPress: PropTypes.func,
text: PropTypes.string,
children: PropTypes.string,
navigator: PropTypes.object
}
getText () {
const buttonText = this.props.text || this.props.children || ''
return buttonText.toUpperCase()
}
render () {
console.tron.log('roundedButton styles:', styles)
return (
<TouchableOpacity style={styles.button} onPress={this.props.onPress}>
<Text style={styles.buttonText}>{this.getText()}</Text>
</TouchableOpacity>
)
}
}
with its styles:
import { StyleSheet } from 'react-native'
import { Fonts, Colors, Metrics } from '../../Themes/'
export default StyleSheet.create({
button: {
height: 45,
borderRadius: 5,
marginHorizontal: Metrics.section,
marginVertical: Metrics.baseMargin,
backgroundColor: Colors.fire,
justifyContent: 'center'
},
buttonText: {
color: Colors.snow,
textAlign: 'center',
fontWeight: 'bold',
fontSize: Fonts.size.medium,
marginVertical: Metrics.baseMargin
}
})
I get the expected view :
However, with my BottomBar component I get:
One thing to notice is that the debugGreen style is just a border that should wrap around my BottomBar component and it is shown flat, but the icons within it render lower, and the debugYellow styled box around the icon is shown around the icon as expected, just shifted a whole way down.
If your mainContainer's view is flex : 1 or height : 100%, you should divide the child's height by 8:2 or the flex by 8:2.
Example
<View style={styles.mainContainer}> // flex: 1
<View style={styles.container}> // flex : 0.8
...
</View>
<View style={styles.bottom}> // flex : 0.2
<BottomBar />
</View>
</View>