I tried to make the simplest possible shared element transition with text but it didn't work at all. The text does not move smoothly at all. I read the documentation and followed the steps but no luck. So my code so far -
App.js
import {NavigationContainer} from '#react-navigation/native';
import * as React from 'react';
import {createSharedElementStackNavigator} from 'react-navigation-shared-element';
import DetailScreen from './DetailScreen';
import ListScreen from './ListScreen';
const Stack = createSharedElementStackNavigator();
const App = ({navigation}) => {
return (
<NavigationContainer>
<Stack.Navigator
initialRouteName="List"
screenOptions={{
headerShown: false,
}}>
<Stack.Screen name="MainScreen" component={ListScreen} />
<Stack.Screen
name="DetailScreen"
component={DetailScreen}
options={navigation => ({
headerBackTitleVisible: false,
cardStyleInterpolator: ({current: {progress}}) => {
return {
cardStyle: {
opacity: progress,
},
};
},
})}
sharedElements={route => {
const {data} = route.params;
console.log(data);
return [
{
id: `item.${data.id}`,
animation: 'move',
resize: 'stretch ',
align: 'center-top',
},
];
}}
/>
</Stack.Navigator>
</NavigationContainer>
);
};
export default App;
ListScreen.js -
import * as React from 'react';
import {Text, TouchableOpacity, View} from 'react-native';
import {SharedElement} from 'react-native-shared-element';
const ListScreen = props => {
const {navigation} = props;
const persons = [
{
id: '1',
name: 'Earnest Green',
},
{
id: '2',
name: 'Winston Orn',
},
{
id: '3',
name: 'Carlton Collins',
},
{
id: '4',
name: 'Malcolm Labadie',
},
{
id: '5',
name: 'Michelle Dare',
},
];
return (
<View
style={{
flex: 1,
padding: 50,
}}>
{persons.map(person => {
return (
<TouchableOpacity
onPress={() => navigation.navigate('DetailScreen', {data: person})}>
<SharedElement id={`item.${person.id}`}>
<Text style={{padding: 20, fontSize: 15, marginTop: 5}}>
{person.name}
</Text>
</SharedElement>
</TouchableOpacity>
);
})}
</View>
);
};
export default ListScreen;
And DetailScreen.js -
import * as React from 'react';
import {Text, View} from 'react-native';
import {SharedElement} from 'react-navigation-shared-element';
const DetailScreen = ({route}) => {
const {data} = route.params;
return (
<View style={{flex: 1, justifyContent: 'flex-start', alignItems: 'center'}}>
<SharedElement id={`item.${data.id}`}>
<Text style={{fontSize: 22}}>{data.name}</Text>
</SharedElement>
</View>
);
};
export default DetailScreen;
So my transition now look like
it is not smooth at all. How can i fix that?
Sorry for my bad English!
You are importing the SharedElement from react-native-shared-element.
You should import it from react-navigation-shared-element
Related
Would anyone be able to give me help regarding React Navigation with Expo? The issue is with the drawer component where the 'Hamburger' icon isn't opening or closing the component when a user presses the icon. However, it does open/close on a default swipe gesture from React Navigation. Please see below for my code:
Router:
import React from 'react';
import { NavigationContainer, DrawerActions } from '#react-navigation/native';
import { createDrawerNavigator } from '#react-navigation/drawer';
import { IconButton } from 'react-native-paper'
import i18n from '../i18n/i18n';
//Theme
import Theme from '../theme/theme'
//Components
import Menu from '../components/Menu'
//Import Interfaces
import { RootDrawerParamList } from '../utils/typescript/type.d';
import { IProps } from '../utils/typescript/props.d';
//Import Screens
import Screen1 from '../screens/Screen1';
import Screen2 from '../screens/Screen2';
import SettingsScreen from '../screens/Settings';
const Drawer = createDrawerNavigator<RootDrawerParamList>();
export default class Router extends React.Component<IProps, any> {
constructor(props: IProps) {
super(props);
}
render() {
return (
<NavigationContainer>
<Drawer.Navigator
initialRouteName='Screen1'
drawerContent={(props: any) => <Menu {...props} />}
screenOptions={({
swipeEnabled: true
})}>
<Drawer.Screen
name="Screen1"
component={Screen1}
initialParams={{ i18n: i18n, Theme: Theme }}
options={({route, navigation} : any) => ({
headerRight: () => (<IconButton icon="cog" size={24} color={Theme.colors.text} onPress={() => navigation.navigate('Settings')} />),
route: {route},
navigation: {navigation}
})}
/>
<Drawer.Screen
name="Settings"
component={SettingsScreen}
initialParams={{ i18n: i18n, Theme: Theme }}
options={({route, navigation} : any) => ({
headerTitle: i18n.t('settings', 'Settings'),
headerLeft: () => (<IconButton icon="arrow-left" color={Theme.colors.text} size={24} onPress={() => navigation.goBack()} />),
route: {route},
navigation: {navigation}
})}
/>
<Drawer.Screen
name="Screen2"
component={Screen2}
initialParams={{ i18n: i18n, Theme: Theme }}
options={({route, navigation} : any) => ({
route: {route},
navigation: {navigation}
})}
/>
</Drawer.Navigator>
</NavigationContainer>
);
}
}
Menu
import React from 'react';
import { FlatList, StyleSheet, View } from 'react-native';
import { List, Title } from 'react-native-paper';
import { getDefaultHeaderHeight } from '#react-navigation/elements';
import { DrawerItem } from '#react-navigation/drawer';
import { useSafeAreaFrame, useSafeAreaInsets } from 'react-native-safe-area-context';
//Import Interfaces
import { IListItem } from '../utils/typescript/types.d';
import { IPropsMenu } from '../utils/typescript/props.d';
import { IStateMenu } from '../utils/typescript/state.d';
//A function is used to pass the header height, using hooks.
function withHeightHook(Component: any){
return function WrappedComponent(props: IPropsMenu) {
/*
Returns the frame of the nearest provider. This can be used as an alternative to the Dimensions module.
*/
const frame = useSafeAreaFrame();
/*
Returns the safe area insets of the nearest provider. This allows manipulating the inset values from JavaScript. Note that insets are not updated synchronously so it might cause a slight delay for example when rotating the screen.
*/
const insets = useSafeAreaInsets();
return <Component {...props} headerHeight={getDefaultHeaderHeight(frame, false, insets.top)} />
}
}
class Menu extends React.Component<IPropsMenu, IStateMenu> {
constructor(props: IPropsMenu) {
super(props);
this.state = {
menu: [
{
name: 'screen1.name',
fallbackName: 'Screen 1',
icon: 'dice-multiple-outline',
iconFocused: 'dice-multiple',
onPress: this.props.navigation.navigate.bind(this, 'screen1')
},
{
name: 'screen2.name',
fallbackName: 'Screen 2',
icon: 'drama-masks',
iconFocused: 'drama-masks',
onPress: this.props.navigation.navigate.bind(this, 'screen2')
}
]
}
}
renderItem = (item : IListItem) => {
const { i18n } = this.props.state.routes[0].params;
return (
<DrawerItem
label={ i18n.t(item.name, item.fallbackName) }
onPress={ item.onPress ? item.onPress: () => {} }
icon={ ({ focused, color, size }) => <List.Icon color={color} style={[styles.icon, {width: size, height: size }]} icon={(focused ? item.iconFocused : item.icon) || ''} /> }
/>
);
};
render() {
const { headerHeight } = this.props;
const { menu } = this.state;
const { Theme } = this.props.state.routes[0].params;
return (
<View>
<View style={{
backgroundColor: Theme.colors.primary,
height: headerHeight ?? 0,
}}>
<View style={{
flex: 1,
flexDirection: 'column',
justifyContent: 'flex-end',
}}>
<View style={{
flexDirection: 'row',
alignItems: 'center',
marginBottom: 5,
marginLeft: 5
}}>
<Title style={{ color: Theme.colors.text, marginLeft: 5 }}>
Title
</Title>
</View>
</View>
</View>
<FlatList
data={menu}
keyExtractor={item => item.name}
renderItem={({item}) => this.renderItem(item)}
/>
</View>
);
};
}
export default withHeightHook(Menu);
const styles = StyleSheet.create({
icon: {
alignSelf: 'center',
margin: 0,
padding: 0,
height:20
},
logo: {
width: 24,
height: 24,
marginHorizontal: 8,
alignSelf: 'center'
},
});
The solution to my issue was to encapsulate the drawer component in a native stack component. The 'Hamburger' icon works as expected, thanks for all the help and suggestions.
// Import Screens
import DrawRouter from './DrawRouter';
const Stack = createNativeStackNavigator<RootStackParamList>();
export default (): React.ReactElement => {
return (
<NavigationContainer>
<Stack.Navigator screenOptions={{ headerShown: false }}>
<Stack.Screen name="Main" component={DrawRouter} />
</Stack.Navigator>
</NavigationContainer>
);
};
Add the toogleDrawer() method to your onPress event on your Drawer.Navigator component:
onPress={()=> navigation.toggleDrawer()
Hello guys so I wanted to add a navigation DRAWER inside my main screen and I did not know how to nest it with the already existing stack navigator ,
this is my navigation component :
import React from "react";
import { NavigationContainer } from "#react-navigation/native";
import { createStackNavigator } from "#react-navigation/stack";
import ProductsOverviewScreen from "../screens/shop/ProductsOverviewScreen";
import ProductDetails from "../screens/shop/ProductDetailScreen";
import { HeaderButtons,Item } from "react-navigation-header-buttons";
import HeaderButton from '../components/UI/HeaderButton'
import CartScreen from "../screens/shop/CartScreen";
import OrdersScreen from "../screens/shop/OrdersScreen";
const RootNavigation=()=> {
const Stack = createStackNavigator();
const NavigationDrawerStructure = (props)=> {
//Structure for the navigatin Drawer
const toggleDrawer = () => {
//Props to open/close the drawer
props.navigationProps.toggleDrawer();
};
return (
<View style={{ flexDirection: 'row' }}>
<TouchableOpacity onPress={()=> toggleDrawer()}>
{/*Donute Button Image */}
<Image
source={{uri: 'https://raw.githubusercontent.com/AboutReact/sampleresource/master/drawerWhite.png'}}
style={{ width: 25, height: 25, marginLeft: 5 }}
/>
</TouchableOpacity>
</View>
);
}
const screenOptions ={
headerShown:true,
headerStyle: {
backgroundColor: 'white',},
headerTintColor: 'aqua',
headerTitleStyle: {
fontWeight: 'bold',
},
};
return(
<NavigationContainer>
<Stack.Navigator initialRouteName='ProductsOverview' screenOptions={screenOptions}>
<Stack.Screen name='ProductsOverview' component={ProductsOverviewScreen} options={({navigation,route})=>({title:'All Products',headerTitleStyle:{fontFamily:'open-sans-bold'},
headerRight:()=>( <HeaderButtons HeaderButtonComponent={HeaderButton}><Item title ='Cart' iconName='md-cart' onPress={()=>{navigation.navigate('CartScreen')}}/></HeaderButtons>)})}/>
<Stack.Screen name='ProductsDetail' component={ProductDetails} options={({route})=>({title:route.params.productTitle,headerTitleStyle:{fontFamily:'open-sans-bold'}})} />
<Stack.Screen name='CartScreen' component={CartScreen} options={{title:'Cart Items', headerTitleStyle:{fontFamily:'open-sans-bold'}}} />
<Stack.Screen name='OrdersScreen' component={OrdersScreen} options={{title:'Orders '}}/>
</Stack.Navigator>
</NavigationContainer>
)
}
export default RootNavigation;
and this is my app.js
import { StatusBar } from 'expo-status-bar';
import { StyleSheet } from 'react-native';
import {createStore , combineReducers} from 'redux';
import { Provider} from 'react-redux';
import AppLoading from 'expo-app-loading';
import * as Font from 'expo-font';
import productsReducer from './store/reducers/products';
import {composeWithDevTools} from 'redux-devtools-extension'
import RootNavigation from './navigation/ShopNavigation';
import cartReducer from './store/reducers/cart'
import { useState } from 'react';
import ordersReducer from './store/reducers/orders'
const rootReducer=combineReducers({
products: productsReducer,
cart: cartReducer,
orders:ordersReducer,
});
const store = createStore(rootReducer,composeWithDevTools());
const fetchFonts=()=>{
return Font.loadAsync({
'open-sans': require('./assets/fonts/OpenSans-Regular.ttf'),
'open-sans-bold': require('./assets/fonts/OpenSans-Bold.ttf')
})
}
export default function App() {
const [fontLoaded,setfontLoaded]= useState(false);
if (!fontLoaded) {
return (
<AppLoading
startAsync={fetchFonts}
onFinish={()=>setfontLoaded(true)}
onError={console.warn}
/>
);
}
return (
<Provider store={store}>
<RootNavigation />
</Provider>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
},
});
can you give me an idea how to nest them together I tried using the docs but still full of errors
and Thanks
Drawer Navigator must be a parent to both Stack and Tab navigators. With that knowledge, let we refactor our code as below:
import React from "react";
import { NavigationContainer } from "#react-navigation/native";
import { createStackNavigator } from "#react-navigation/stack";
import ProductsOverviewScreen from "../screens/shop/ProductsOverviewScreen";
import ProductDetails from "../screens/shop/ProductDetailScreen";
import { HeaderButtons, Item } from "react-navigation-header-buttons";
import HeaderButton from "../components/UI/HeaderButton";
import CartScreen from "../screens/shop/CartScreen";
import OrdersScreen from "../screens/shop/OrdersScreen";
import { createDrawerNavigator } from "#react-navigation/drawer";
const RootNavigation = () => {
const Stack = createStackNavigator();
const Drawer = createDrawerNavigator();
const AppStack = () => (
<Stack.Navigator
initialRouteName="ProductsOverview"
screenOptions={screenOptions}
>
<Stack.Screen
name="ProductsOverview"
component={ProductsOverviewScreen}
options={({ navigation, route }) => ({
title: "All Products",
headerTitleStyle: { fontFamily: "open-sans-bold" },
headerRight: () => (
<HeaderButtons HeaderButtonComponent={HeaderButton}>
<Item
title="Cart"
iconName="md-cart"
onPress={() => {
navigation.navigate("CartScreen");
}}
/>
</HeaderButtons>
),
})}
/>
<Stack.Screen
name="ProductsDetail"
component={ProductDetails}
options={({ route }) => ({
title: route.params.productTitle,
headerTitleStyle: { fontFamily: "open-sans-bold" },
})}
/>
<Stack.Screen
name="CartScreen"
component={CartScreen}
options={{
title: "Cart Items",
headerTitleStyle: { fontFamily: "open-sans-bold" },
}}
/>
<Stack.Screen
name="OrdersScreen"
component={OrdersScreen}
options={{ title: "Orders " }}
/>
</Stack.Navigator>
);
return (
<NavigationContainer>
<Drawer.Navigator>
<Drawer.Screen name="MainStack" component={AppStack} />
</Drawer.Navigator>
</NavigationContainer>
);
};
export default RootNavigation;
I omitted component code below as can't access drawer.
const NavigationDrawerStructure = (props)=> {
//Structure for the navigatin Drawer
const toggleDrawer = () => {
//Props to open/close the drawer
props.navigationProps.toggleDrawer();
};
return (
<View style={{ flexDirection: 'row' }}>
<TouchableOpacity onPress={()=> toggleDrawer()}>
{/*Donute Button Image */}
<Image
source={{uri: 'https://raw.githubusercontent.com/AboutReact/sampleresource/master/drawerWhite.png'}}
style={{ width: 25, height: 25, marginLeft: 5 }}
/>
</TouchableOpacity>
</View>
);
}
Here a minified version of working implementation
https://snack.expo.dev/#emmbyiringiro/69dc5b
I am learning React native and was trying to build an app. However, the app is stuck on a white screen and doesn't show anything nor gives any error. This code is going to render a flatlist from an array and will have a delete to swipe button on the right. I am not getting any errors though.
Message.js
import React, { useState } from 'react'
import {
View,
Text,
StyleSheet,
FlatList,
SafeAreaView,
StatusBar,
ItemSeparatorComponent,
Platform
} from 'react-native'
import ListItem from '../components/ListItem'
import ListItemSeparator from '../components/ListItemSeparator'
import DeleteSwipe from '../components/DeleteSwipe'
const messages = [
{
id: 1,
name: 'T1',
description: 'D2',
image: require('../assets/mosh.jpg')
},
{
id: 2,
name: 'T2',
description: 'D2',
image: require('../assets/mosh.jpg')
},
{
id: 3,
name: 'T3',
description: 'D3',
image: require('../assets/mosh.jpg')
},
{
id: 4,
name: 'T4',
description: 'D4',
image: require('../assets/mosh.jpg')
}
]
export default function Message () {
const [messages, setMessage] = useState(messages)
const handleDelete = messages => {
const newMessages = messages.filter(m => m.id != messages.id)
setMessage(newMessages)
}
return (
<SafeAreaView style={styles.screen}>
<FlatList
data={messages}
keyExtractor={messages => messages.id.toString()}
renderItem={({ item }) => (
<ListItem
name={item.name}
description={item.description}
image={item.image}
onPress={() => console.log('touched', item)}
renderRightActions={() => (
<DeleteSwipe onPress={() => handleDelete(item)} />
)}
/>
)}
ItemSeparatorComponent={ListItemSeparator}
/>
<FlatList />
</SafeAreaView>
)
}
const styles = StyleSheet.create({
screen: {
padding: Platform.OS === 'android' ? StatusBar.currentHeight : 0
}
})
DeleteSwipe.js
import React from 'react'
import { View, Text, StyleSheet, TouchableWithoutFeedback } from 'react-native'
import Swipeable from 'react-native-gesture-handler/Swipeable'
import { AntDesign } from '#expo/vector-icons'
const DeleteSwipe = props => {
const { renderRightActions } = props
return (
<TouchableWithoutFeedback onPress={console.log('delete it')}>
<View style={styles.container}>
<AntDesign name='delete' size={24} color='white' />
</View>
</TouchableWithoutFeedback>
)
}
const styles = StyleSheet.create({
container: {
width: 70,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#ff5252'
}
})
export default DeleteSwipe
If it is a debugger issue, Restart the debugger if react native debugger is running. and again start
Or it could be a flexbox issue, Try to add or remove display: flex and flex:1 on this and parent.
Or it could be component is too small, Open inspector from dev menu and check component names in screen.
Change onPress={console.log....} to onPress={() => console.log(...
)}
But it seems what you want is onPress={props.onPress}
I was following tutorial and I got 'ReferenceError can't find variable flatlist' error, then I deleted the code and copied from the github to check if I might missed something and it's still didn't work.
import React, {useState} from 'react';
import {StyleSheet, Text, View,FlatList} from 'react-native';
import Header from './components/header';
export default function App () {
const [todos, setTodos] = useState([
{ text: 'buy coffee', key: '1' },
{ text: 'create an app', key: '2' },
{ text: 'play on the switch', key: '3' }
]);
return (
<View style={styles.container}>
<Header />
<View style={styles.content}>
{/* add todo form */}
<View style={styles.list}>
<FlatList
data={todos}
renderItem={({item}) => (
<Text>{item.text}</Text>
)}
/>
</View>
</View>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
},
content:{
padding: 40,
},
list:{
marginTop:20,
}
});
Header :
import React from 'react';
import {StyleSheet, Text, View} from 'react-native';
export default function Header() {
return(
<View style={styles.header}>
<Text style={styles.title}>My Todo List</Text>
</View>
)
}
const styles= StyleSheet.create({
header:{
height: 80,
paddingTop: 38,
backgroundColor: 'red',
},
title:{
textAlign: 'center',
color:'#fff',
fontSize: 20,
fontWeight:'bold',
}
});
export default Header;
Perhaps something changed in the version or something else. I will be grateful if you can tell how I can fix the error.
Edit: I changed the casing from Flatlist to FlatList and I got error 'Element type invalid: expected a string (for built- in components)'.
\ Screenshot
change case of Flatlist import as:
import {StyleSheet, Text, View,FlatList} from 'react-native';
check export of your header component. You have exported Header Component two time.
Try Replace Flatlist with FlatList
Correct: import {StyleSheet, Text, View,FlatList} from 'react-native';
Also, try to export as Class, if it's entry point:
import React, { Component } from 'react';
export default class App extends Component {
state = {
todos: [
{ text: 'buy coffee', key: '1' },
{ text: 'create an app', key: '2' },
{ text: 'play on the switch', key: '3' },
],
};
render() {
const { todos } = this.state;
return (
<View style={styles.container}>
<Header />
<View style={styles.content}>
{/* add todo form */}
<View style={styles.list}>
<FlatList
data={todos}
renderItem={({ item }) => <Text>{item.text}</Text>}
/>
</View>
</View>
</View>
);
}
}
I need to use navigation when pressing the bag icon in the header. When I press it, I get the following error:
undefined is not an object (evaluating '_this.props.navigation')
The thing is I need to use it inside a Stack.Screen component, but props.navigation always return undefined.
App.js file:
import React, { Component } from 'react';
import {
Button,
Text,
TextInput,
View,
StyleSheet,
TouchableOpacity,
Image,
} from 'react-native';
import { Header } from 'react-navigation-stack';
import { NavigationContainer } from '#react-navigation/native';
import { createStackNavigator } from '#react-navigation/stack';
import TelaInicial from './components/telaInicial';
import TelaCarrinho from './components/telaCarrinho';
const Stack = createStackNavigator();
export default function AppContainer() {
return (
<NavigationContainer>
<Stack.Navigator initialRouteName="Inicial">
<Stack.Screen
name="Inicial"
component={TelaInicial}
options={{
title: '',
headerTintColor: 'white',
headerStyle: { backgroundColor: '#6b39b6', height: 100 },
height: Header.height,
headerLeft: null,
headerTitle: (
<View>
<TouchableOpacity
onPress={() => {
this.props.navigation.navigate('Carrinho');
}}>
<Image
style={{
width: 29,
height: 29,
marginTop: 0,
marginLeft: 170,
}}
source={require('./assets/shopping bag.png')}
/>
</TouchableOpacity>
</View>
),
}}
/>
<Stack.Screen
name="Carrinho"
component={TelaCarrinho}
options={{
title: '',
headerTintColor: 'white',
headerStyle: { backgroundColor: '#6b39b6', height: 100 },
height: Header.height,
headerBackTitle: 'Voltar',
headerTitle: 'Carrinho'.toUpperCase(),
headerTitleStyle: {
fontSize: 17,
fontWeight: 600,
},
}}
/>
</Stack.Navigator>
</NavigationContainer>
);
}
Do you guys have any idea how I can fix it?
I have a link to Expo: https://snack.expo.io/#rapolasls/eager-crackers
Thank you!
Per React Navigation v5 documentation on createStackNavigator, the header property can be either an object or function.
We use it as a function below to gain access to navigation property. 👍
import React from "react";
import { View, Text, TouchableOpacity, } from "react-native";
import { NavigationContainer } from '#react-navigation/native';
import { createStackNavigator } from '#react-navigation/stack';
const Stack = createStackNavigator();
const Placeholder = (props) => {
const {
name,
backgroundColor,
} = props;
return (
<View style={{ flex: 1, backgroundColor, justifyContent: "center", alignItems: "center", }}>
<Text style={{ fontSize: 20, color: "white", }}>{ name }</Text>
</View>
)
}
const ScreenA = (props) => {
return <Placeholder name="Screen A" backgroundColor="steelblue" />
}
const ScreenB = (props) => {
return <Placeholder name="Screen B" backgroundColor="tomato" />
}
const RootNavigator = () => {
return (
<Stack.Navigator>
<Stack.Screen component={ScreenA} name="a" options={({ navigation }) => {
// navigation object available
const navigateToB = () => { navigation.navigate("b") };
return {
headerTitle: () => {
return (
<TouchableOpacity onPress={navigateToB} style={{ backgroundColor: "green", justifyContent: "flex-end", alignItems: "center", }}>
<Text style={{ fontSize: 20, color: "white", }}>{ "Screen A" }</Text>
</TouchableOpacity>
)
}
}
}} />
<Stack.Screen component={ScreenB} name="b" options={{ headerTitle: "Screen B" }} />
</Stack.Navigator>
);
}
export default function() {
return (
<NavigationContainer>
<RootNavigator />
</NavigationContainer>
);
}