Icons are not displaying in HeaderButtons. Instead the text given for fallback is displaying only.
Here is my Code for component:
import React from "react";
import { Platform } from "react-native";
import { HeaderButton } from 'react-navigation-header-buttons';
import { Ionicons } from 'react-native-vector-icons';
import Colors from '../constants/Colors';
const CustomHeaderButton = props => {
return (
<HeaderButton
{...props}
IconComponent={Ionicons}
iconSize={23}
color={Platform.OS === "android" ? "white" : Colors.primaryColor}
/>
);
};
export default CustomHeaderButton;
Here is the file in which I imported it:
import React from 'react';
import { View, Text, Button, StyleSheet } from 'react-native';
import { HeaderButtons, Item } from 'react-navigation-header-buttons';
import { MEALS } from '../data/dummy-data';
import HeaderButton from '../components/HeaderButton';
const MealDetailScreen = props => {
const mealId = props.navigation.getParam("mealId");
const selectedMeal = MEALS.find(meal => meal.id === mealId);
return (
<View style={styles.screen}>
<Text>{selectedMeal.title}</Text>
<Button title="Go back to Categories!" onPress={() => {
props.navigation.popToTop();
}} />
</View>
);
}
MealDetailScreen.navigationOptions = (navigationData) => {
const mealId = navigationData.navigation.getParam("mealId");
const selectedMeal = MEALS.find(meal => meal.id === mealId);
return {
headerTitle: selectedMeal.title,
headerRight: () => (
<HeaderButtons HeaderButtonComponent={HeaderButton}>
<Item
title="Favorite"
iconName="star"
onPress={() => {
console.log("Mark as favorite.");
}}
/>
</HeaderButtons>
)
};
};
const styles = StyleSheet.create({
screen: {
flex: 1,
justifyContent: "center",
alignItems: "center",
// backgroundColor: "white"
}
});
export default MealDetailScreen;
It is not giving any error and giving the output in console. But icon for star is not displaying.
add the below code in android/app/build.gradle and re-run the app.
project.ext.vectoricons = [
iconFontNames: [ 'Ionicons.ttf' ] // Name of the font files you want to
copy
]
apply from: "../../node_modules/react-native-vector-icons/fonts.gradle"
I got the error.
Instead of this:
import { Ionicons } from 'react-native-vector-icons';
I added this:
import Ionicons from 'react-native-vector-icons/Ionicons';
and icon appeared.
Hi there you can fix this issue by navigating to the android/app/build.gradle
and paste this line at the top and re-run the app by react-native run-android
apply from: "../../node_modules/react-native-vector-icons/fonts.gradle"
Related
There are four components on a screen and only three out of four are rendering. <popDown/> is the component that isn't rendering. When I save the specific component's file the components get rendered. Note: I am saving an already fully updated file. It is running with no errors
The Screen
import react from 'react';
import {View,ScrollView} from 'react-native';
import { SafeAreaView, } from 'react-navigation';
import { PrProvider } from '../appFunctions/PrContext';
import PopDown from '../Components/PRForm/popDown';
import RepsWeightTextInput from '../Components/PRForm/RepsWeightTextInput';
import NotesInput from '../Components/PRForm/NotesInput';
import SubmitPr from '../Components/PRForm/SubmitPr';
const PrEnteryScreen = ({}) => {
return(
<View style = {{height:'100%',width:'100%',backgroundColor:'#141212'}}>
<SafeAreaView style = {{alignItems:'center'}}>
{/**
* use context for pr information
*/}
<PrProvider>
<PopDown />
<RepsWeightTextInput/>
<NotesInput/>
<SubmitPr/>
</PrProvider>
</SafeAreaView>
</View>
);
};
export default PrEnteryScreen;
popdown component
import { useContext, useEffect, useState } from "react";
import { TouchableOpacity,StyleSheet,View,LayoutAnimation,UIManager,Platform,useFocusEffect } from "react-native";
import { Children } from "react/cjs/react.production.min";
import SelectExerciseButton, { setIsOpen } from "./SelectExerciseButton";
import SelectExerciseModal from "../../Screens/SelectExerciseModal";
import { EXERCISE_DATA } from "../../Screens/SelectExerciseModal";
import { PrContext, PrProvider } from "../../appFunctions/PrContext";
if (
Platform.OS === "android" &&
UIManager.setLayoutAnimationEnabledExperimental
) {
UIManager.setLayoutAnimationEnabledExperimental(true);
}
const PopDown = () => {
const value = useContext(PrContext)
const [isOpen,setIsOpen] = useState(false)
const [listHeight,setListHeight] = useState(0)
const [textName,setTextName] = useState(value.exercise);//eventually want to change text based on exercise state
const toggleOpen = () => {
setIsOpen(value => !value);
LayoutAnimation.configureNext(LayoutAnimation.Presets.spring);
setTextName(value.exercise);
console.log(value.exercise);
}
useEffect(() =>{
EXERCISE_DATA.forEach(()=>{
setListHeight(value => value+50)
})
},[isOpen])
return(
<>
<TouchableOpacity
onPress = {toggleOpen}
>
<SelectExerciseButton />
</TouchableOpacity>
<View>
<SelectExerciseModal style = {isOpen ? styles.show: styles.hidden} listHeight = {listHeight} name = {textName}/>
</View>
</>
)
}
const styles = StyleSheet.create({
hidden:{
height:0,
},
show:{ backgroundColor: '#9B9A9A', width: 200 }
});
export default PopDown;
What I tried
I changed the hidden style height to see if it would render the list that is supposed to pop out of the button. The list did render which means the <selectExerciseButton/> is the only thing not rendering in <popDown/>.
const styles = StyleSheet.create({
hidden:{
height:100,
},
show:{ backgroundColor: '#9B9A9A', width: 200 }
});
<TouchableOpacity
onPress = {toggleOpen}
>
{children}
</TouchableOpacity>
<View>
<SelectExerciseModal style = {isOpen ? styles.show: styles.hidden} listHeight = {listHeight} name = {textName}/>
</View>
<PrProvider>
<PopDown>
<SelectExerciseButton/>
</PopDown>
<RepsWeightTextInput/>
<NotesInput/>
<SubmitPr/>
</PrProvider>
SelectExerciseButton
import { useNavigation,useFocusEffect } from "#react-navigation/native";
import { SafeAreaView, StyleSheet, Text, TouchableOpacity, View,LayoutAnimation } from "react-native";
import { useContext, useState,useEffect } from "react";
import { PrContext } from "../../appFunctions/PrContext";
/**
*
* #returns button that navigates to the a modal to select an exercise
*/
if (
Platform.OS === "android" &&
UIManager.setLayoutAnimationEnabledExperimental
) {
UIManager.setLayoutAnimationEnabledExperimental(true);
}
const SelectExerciseButton = () => {
const value = useContext(PrContext)
return(
<>
<View style = {styles.background}>
<Text style = {styles.Text}> {value.exercise} </Text>
</View>
</>
);
};
styles = StyleSheet.create({
background:{
backgroundColor: '#9B9A9A',
width: 335,
borderRadius:41,
alignItems:'center',
marginHorizontal:25,
height:200,
justifyContent:'center'
},
Text:{
fontWeight:'bold',
fontSize:40,
color:'white',
alignItems:'center'
}
})
export default SelectExerciseButton;
I am using react-navigation 5 in my mobile app and I am stuck in implementing a log-off feature.
The scenario is I have a stack navigator and a bottom tab navigator in my app. The app starts with the stack navigator (Login feature and Reset Password Feature) and on login goes to the dashboard Page which is from the bottom tab navigator. Now on the Dashboard page, I am implementing a logout feature which when clicked should take me to the login page (part of stack navigator), and no matter what I try it keeps giving me errors like these
The action 'RESET' with payload {"index":0,"routes":[{"name":"AuthNavigator"}]} was not handled by any navigator.
Here are my code snippets right from start
Component Called from App.js
import React, { useState, useEffect, useContext } from "react";
import { ActivityIndicator } from "react-native";
import AsyncStorage from '#react-native-async-storage/async-storage';
import { Center } from "../../components/Center";
import { AuthContext } from "../authentication/AuthProvider";
import { NavigationContainer } from "#react-navigation/native";
import { AuthNavigator } from "./AuthNavigator";
import { MainTabNavigator } from "./MainTabNavigator";
export default function App() {
const { user, login } = useContext(AuthContext);
const [loading, setLoading] = useState(true);
useEffect(() => {
// check if the user is logged in or not
//AsyncStorage.removeItem("user") //- uncomment this and refresh emulator to start from login screen
AsyncStorage.getItem("user")
.then(userString => {
if (userString) {
login();
}
setLoading(false);
})
.catch(err => {
console.log(err);
});
}, []);
if (loading) {
return (
<Center>
<ActivityIndicator size="large" />
</Center>
);
}
return (
<NavigationContainer>
{user ? <MainTabNavigator /> : <AuthNavigator />}
</NavigationContainer>
);
}
AuthNavigator.js
import React from "react";
import { createStackNavigator } from '#react-navigation/stack';
import Login from '../authentication/Login';
import ResetPassword from '../authentication/ResetPassword';
import { MainTabNavigator } from "./MainTabNavigator";
const Stack = createStackNavigator();
export const AuthNavigator = () => {
return (
<Stack.Navigator initialRouteName="Login">
<Stack.Screen name="Login" component={Login} />
<Stack.Screen name="ResetPassword" options={{headerTitle: "Reset Password"}} component={ResetPassword} />
</Stack.Navigator>
);
}
MainTabNavigator.js
import * as React from 'react';
import { Text, View, Image, StyleSheet, Platform } from 'react-native';
import { createBottomTabNavigator } from '#react-navigation/bottom-tabs';
import DashboardView from '../dashboard/DashboardView';
import Search from '../searchLoan/Search';
import { colors } from '../../styles';
const iconHome = require('../../../assets/images/tabbar/home.png');
const iconGrids = require('../../../assets/images/tabbar/grids.png');
const searchIcon = require('../../../assets/images/pages/search_24px.png');
const Tab = createBottomTabNavigator();
const tabData = [
{
name: 'Dashboard',
component: DashboardView,
icon: iconHome,
},
{
name: 'Search',
component: Search,
icon: searchIcon,
},
];
export const MainTabNavigator = () => {
return (
<Tab.Navigator tabBarOptions={{ style: { height: Platform.OS === 'ios' ? 90 : 50 } }}>
{tabData.map((item, idx) => (
<Tab.Screen
key={`tab_item${idx + 1}`}
name={item.name}
component={item.component}
options={{
tabBarIcon: ({ focused }) => (
<View style={styles.tabBarItemContainer}>
<Image
resizeMode="contain"
source={item.icon}
style={[styles.tabBarIcon, focused && styles.tabBarIconFocused]}
/>
</View>
),
tabBarLabel: ({ focused }) => <Text style={{ fontSize: 12, color: focused ? colors.primary : colors.gray }}>{item.name}</Text>,
title: item.name,
}}
/>
))}
</Tab.Navigator>
);
};
const styles = StyleSheet.create({
tabBarItemContainer: {
alignItems: 'center',
justifyContent: 'center',
borderBottomWidth: 2,
borderBottomColor: colors.white,
paddingHorizontal: 10,
bottom: Platform.OS === 'ios' ? -5 : 0,
},
tabBarIcon: {
width: 23,
height: 23,
},
tabBarIconFocused: {
tintColor: colors.primary,
},
});
DashboardView.js
import React , {useContext }from 'react';
import { StyleSheet, View, TouchableOpacity, Text } from 'react-native';
import {Header} from 'react-native-elements';
import AntIcon from "react-native-vector-icons/AntDesign";
import { colors, fonts } from '../../styles';
import AmountDetails from './AmountDetails';
import DashboardFields from './DashboardFields';
import { AuthContext } from "../authentication/AuthProvider";
import { CommonActions } from "#react-navigation/native";
export default function DashboardView(props) {
const appLogOut = () => {
const { logout } = useContext(AuthContext);
console.log('props', props)
if(logout){
// console.log("Navigation Object", navigation)
props.navigation.dispatch(
CommonActions.reset({
index: 0,
routes: [{ name: "AuthNavigator" }],
}));
}
}
return (
<View style={styles.container}>
<Header containerStyle = {{backgroundColor: colors.primary}}
centerComponent={{ text: 'Dashboard', style: { color: colors.white, backgroundColor: colors.primary } }}
rightComponent = <TouchableOpacity onPress={appLogOut()}><AntIcon name="logout" color="white" size={25}/></TouchableOpacity>
/>
<View style={styles.container}>
<View>
<AmountDetails />
</View>
<View style={styles.dashboardFields}>
<DashboardFields />
</View>
</View>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: colors.gray,
},
dashboardFields: {
marginTop: 20,
},
});
You should try calling the login screen directly, not the whole stack.
CommonActions.reset({
index: 0,
routes: [{ name: "Login" }],
}));
As the other answer said, you have incorrect route name (AuthNavigator).
However, you're conditionally defining screens based on if the user is logged in. You don't need to do anything extra when logging out. Conditionally defining screens means React Navigation can automatically handle which screen to show when the conditional changes.
So you need to remove the code which does reset.
From the docs:
It's important to note that when using such a setup, you don't need to manually navigate to the Home screen by calling navigation.navigate('Home') or any other method. React Navigation will automatically navigate to the correct screen when isSigned in changes - Home screen when isSignedIn becomes true, and to SignIn screen when isSignedIn becomes false. You'll get an error if you attempt to navigate manually.
More details: https://reactnavigation.org/docs/auth-flow/
I have two checkboxes (from react-native elements), let's call them box a and box b, where it should only be possible to have one of them checked at a time (no multiple selection), iow - if box a is checked, it is not possible to check box b. So as of this moment, if I were to have checked box a by mistake, I need to uncheck box a manually by clicking it again, in order to check box b. However, I want to be able to automatically uncheck box a by clicking and checking box b - if that makes any sense.
I have tried to look at both issue 54111540 and others, but none of the answers there seem to help with what I want to achieve.
My code:
import React, { useState } from 'react';
import { View, Text, StyleSheet, TouchableOpacity, } from 'react-native';
import { CheckBox } from 'react-native-elements';
import { Ionicons } from '#expo/vector-icons';
import { slider } from '../../components/SliderStyle';
import { useDispatch } from 'react-redux';
import { addfirstrole } from '../../redux/actions/index';
import store from '../../redux/store';
import * as firebase from 'firebase';
const RoleScreen = ({ navigation }) => {
const dispatch = useDispatch()
const addFirstRole = firstRole => dispatch(addfirstrole(firstRole))
const [landlordChecked, setLandlordChecked ] = useState(false)
const [tenantChecked, setTenantChecked] = useState(false)
const user = firebase.auth().currentUser
return (
<View>
<Text>Role screen</Text>
<CheckBox
title='Jeg er utleier'
checkedIcon='dot-circle-o'
uncheckedIcon='circle-o'
checked={landlordChecked}
onPress={tenantChecked ? () => setLandlordChecked(false) : () => setLandlordChecked(!landlordChecked)}
/>
<CheckBox
title='Jeg er leietaker'
checkedIcon='dot-circle-o'
uncheckedIcon='circle-o'
checked={tenantChecked}
onPress={landlordChecked ? () => setTenantChecked(false) : () => setTenantChecked(!tenantChecked)}
/>
<TouchableOpacity onPress={() => { navigation.navigate('Search'); addFirstRole(user.uid); console.log(store.getState()); }}>
<View style={slider.buttonStyle}>
<Text style={slider.textStyle}>Neste</Text>
<Ionicons name='ios-arrow-forward'style={slider.iconStyle} />
</View>
</TouchableOpacity>
</View>
)
}
const styles = StyleSheet.create({})
export default RoleScreen;
Try this, this will help you
import React, { useState } from 'react';
import { View, Text, StyleSheet, TouchableOpacity, } from 'react-native';
import { CheckBox } from 'react-native-elements';
import { Ionicons } from '#expo/vector-icons';
import { useDispatch } from 'react-redux';
import * as firebase from 'firebase';
const RoleScreen = ({ navigation }) => {
const [landlordChecked, setLandlordChecked ] = useState(false)
const [tenantChecked, setTenantChecked] = useState(false)
return (
<View>
<Text>Role screen</Text>
<CheckBox
title='Jeg er utleier'
checkedIcon='dot-circle-o'
uncheckedIcon='circle-o'
checked={landlordChecked}
onPress={landlordChecked ? () => setLandlordChecked(false) : () => [setLandlordChecked(true),setTenantChecked(false)]}
/>
<CheckBox
title='Jeg er leietaker'
checkedIcon='dot-circle-o'
uncheckedIcon='circle-o'
checked={tenantChecked}
onPress={tenantChecked ? () => setTenantChecked(false): () => [setTenantChecked(true),setLandlordChecked(false)]}
/>
</View>
)
}
const styles = StyleSheet.create({})
export default RoleScreen;
Change this according to your requirement. Feel free for doubts
this is How to uncheck other values if one is checked
this is a function we call with onPress
data3.checked is true or falses
data3.filterx.id is filter id
onPress statement is
{data4.map((item) => {
return (
<TouchableOpacity
style={{
flexDirection: "row",
alignItems: "center",
}}
key={item.filterx.id}
onPress={() => handleChange4(item.filterx.id)}
>
<CheckBox checked={item.checked} />
<Text>{item.filterx.title}</Text>
</TouchableOpacity>
);
})}
const handleChange3 = (id) => {
let temp = data3.map((data3) => {
if (id === data3.filterx.id) {
return { ...data3, checked: !data3.checked };
}
return data3;
});
for (var i = 0; i < data3.length; i++) {
data3[i].checked = false;
}
data3.checked = true;
console.log(temp);
setdata3(temp);
};
I am trying to render a FlatList in the home screen using react-navigation after refresing this error message appears:
invariant violation: Objects are not valid as a React child (found: object with keys {screenProps, navigation}). If you meant to render a collection of children, use an array instead.
//App.js
import React from 'react';
import Navigator from './src/Routes/appRoutes';
import { View, Text, StyleSheet } from 'react-native';
import TodoApp from './src/todoApp';
import SingleTodo from './src/components/singleTodo';
const App = () => {
return (
<Navigator />
);
}
const styles = StyleSheet.create(
{
container: {
padding: 40
}
}
)
export default App;
//FlatList screen
import React, { useState } from 'react';
import { View, FlatList } from 'react-native';
import Todos from './components/todos';
import uuid from 'uuid';
const TodoApp = () => {
const [todo, setTodo] = useState([
{
id: uuid(),
title: "FFFFFFFFF",
desc: "first description"
},
{
id: uuid(),
title: "Second title",
desc: "Second description"
}
]
)
return (
<View>
<FlatList
data={todo}
renderItem={({ item }) =>
<Todos title={item.title} desc={item.desc} />}
keyExtractor={item => item.id}
/>
</View>
);
}
export default TodoApp;
//Routes
import { createStackNavigator } from 'react-navigation-stack';
import Todos from './../components/todos';
import SingleTodo from './../components/singleTodo';
import { createAppContainer } from 'react-navigation';
import { Settings } from './../settings';
const screens = {
Home: {
screen: Todos
},
SingleTodo: {
screen: SingleTodo
}
}
const StackScreens = createStackNavigator(screens);
export default createAppContainer(StackScreens);
//Todos screen
import React from 'react';
import { StyleSheet, Text, View, TouchableOpacity } from 'react-native';
import { NavigationNativeContainer } from '#react-navigation/native';
import { createStackNavigator } from '#react-navigation/stack';
const Todos = (props) => {
console.log(props);
const { title, desc } = props;
return (
<View style={styles.container}>
<TouchableOpacity onPress={() => props.navigation.navigate('SingleTodoScreen')}>
<View>{props}</View>
<Text style={styles.listText}>{title}</Text>
</TouchableOpacity>
</View>
)
}
const styles = StyleSheet.create({
container: {
padding: 15,
color: "#000",
borderWidth: 1,
borderColor: "#eee",
},
listText: {
fontSize: 16
}
});
export default Todos;
You need to remove the following line from the code
<View>{props}</View>
props is an object, and you can not write the include the object in your JSX.
So your functional component will be like this.
const Todos = (props) => {
console.log(props);
const { title, desc } = props;
return (
<View style={styles.container}>
<TouchableOpacity onPress={() => props.navigation.navigate('SingleTodoScreen')}>
<Text style={styles.listText}>{title}</Text>
</TouchableOpacity>
</View>
)
}
recently started working on an app using https://github.com/start-react/native-starter-kit
Heres my component:
import React, { Component } from "react";
import { TouchableOpacity } from "react-native";
import { connect } from "react-redux";
import BlankPage2 from "../blankPage2";
import DrawBar from "../drawBar";
import TopNav from "../topNav";
import { DrawerNavigator, NavigationActions } from "react-navigation";
import {
Container,
Header,
Title,
Content,
Text,
Button,
Icon,
Left,
Body,
Right,
Image,
} from "native-base";
import { Grid, Row } from "react-native-easy-grid";
import { setIndex } from "../../actions/list";
import { openDrawer } from "../../actions/drawer";
import styles from "./styles";
class News extends Component {
static navigationOptions = {
header: null
};
render() {
return (
<Container style={styles.container}>
<Header>
<Left>
<Button
transparent
onPress={() => DrawerNav.navigate("DrawerOpen")}>
<Icon active name="menu" />
</Button>
</Left>
<Body>
<Title>News</Title>
</Body>
<Right>
</Right>
</Header>
<Content scrollEnabled={false}>
<TopNav navigation={this.props.navigation}></TopNav>
<Grid style={styles.mt}>
{this.props.list.map((item, i) => (
<Row key={i}>
<TouchableOpacity
style={styles.row}
onPress={() =>
this.props.navigation.navigate("BlankPage", {
name: { item }
})}>
<Image source={{uri: 'https://i.vimeocdn.com/portrait/58832_300x300.jpg'}} />
<Text style={styles.text}>{item}</Text>
</TouchableOpacity>
</Row>
))}
</Grid>
</Content>
</Container>
);
}
}
function bindAction(dispatch) {
return {
setIndex: index => dispatch(setIndex(index)),
openDrawer: () => dispatch(openDrawer())
};
}
const mapStateToProps = state => ({
name: state.user.name,
list: state.list.list
});
const NewsSwagger = connect(mapStateToProps, bindAction)(News);
const DrawNav = DrawerNavigator(
{
News: { screen: NewsSwagger },
BlankPage2: { screen: BlankPage2 }
},
{
contentComponent: props => <DrawBar {...props} />
}
);
const DrawerNav = null;
DrawNav.navigationOptions = ({ navigation }) => {
DrawerNav = navigation;
return {
header: null
};
};
export default DrawNav;
And of course, heres my error:
And i have no clue why this is happening. As soon as i remove the Image tag, error goes away. I can't really export the News Component, becouse i am using the Drawer thingy(check starter-kit-demo).
Edit: Error happens on IOS. Iphone 6 emulator.
You are importing Image from native-base when you should be importing it from react-native
import {
Container,
Header,
Title,
Content,
Text,
Button,
Icon,
Left,
Body,
Right,
Image // remove this one
} from "native-base";
And add
import {
TouchableOpacity,
Image
} from "react-native";
Also you'll have to add a height & width for a proper render.
<Image
style={{width: 300, height: 300}}
source={{uri: 'https://i.vimeocdn.com/portrait/58832_300x300.jpg'}}
/>