Here is my code
import { useState } from "react";
import { useRoute } from "#react-navigation/native";
import { View, Text, Button, FlatList, TouchableOpacity, Pressable } from "react-native";
import { globalStyles } from '../themes/global';
export default function SeatSelectionScreen({ route, navigation }) {
const [seats, setSeats] = useState([
{ key: '1', seat: 'A1' },
{ key: '2', seat: 'A2' },
{ key: '3', seat: 'A3' },
{ key: '4', seat: 'A4' },
]);
}
return (
<View style={globalStyles.container}>
<Text style={globalStyles.mainTitle}>{route.params.title}</Text>
<Text style={globalStyles.mainTitle}>{route.params.genre}</Text>
<FlatList
numColumns={3}
data={seats}
renderItem={({ item }) => (
<TouchableOpacity onPress={() => navigation.navigate('Payment Details Screen', {
title: route.params.title, genre: route.params.genre, details: route.params.details,
time: route.params.time, date: route.params.date, seat: item.seat ,hall: route.params.hall,
url: route.params.url, bgurl: route.params.bgurl, duration:route.params.duration, time: route.params.time
})}
style={globalStyles.itemContainer}>
<Text >{item.seat}</Text>
</TouchableOpacity>
)}
/>
</View>
)
}
I cant figure out what is wrong
Related
Why I get this error Message?
Warning: Each child in a list should have a unique "key" prop.
import * as React from 'react';
import { StyleSheet, Text, View, TouchableOpacity, Image, Dimensions, Animated, FlatList } from 'react-native';
const StoryProfile = () => {
const dataStory = [
{
type: 'NORMAL',
item: {
id: '1',
image: 'https://picsum.photos/200',
}
},
{
type: 'NORMAL',
item: {
id: '2',
image: 'https://picsum.photos/200',
}
},
{
type: 'NORMAL',
item: {
id: '3',
image: 'https://picsum.photos/200',
}
},
{
type: 'NORMAL',
item: {
id: '4',
image: 'https://picsum.photos/200',
}
},
{
type: 'NORMAL',
item: {
id: '5',
image: 'https://picsum.photos/200',
}
},
{
type: 'NORMAL',
item: {
id: '6',
image: 'https://picsum.photos/200',
}
},
];
const Item = React.memo(({ image }) => {
return (
<View>
<Image source={{uri: image}} height={48} width={48} resizeMode="contain" />
</View>
)
});
const renderItem = ({ item }) => {
return (
<Item image={item.image} />
)
};
return (
<View style={styles.container}>
<FlatList
data={dataStory}
keyExtractor={item => item.id}
key={Math.random(1000)}
renderItem={renderItem}
/>
</View>
)
};
const styles = StyleSheet.create({
container: {
flex: 1
}
})
export default StoryProfile;
I have tried a key prop but thats not working. What I am doing wrong ?
........................................................................................................................................................................................................................
No need to have a key prop on a FlatList component:
<FlatList
data={dataStory}
keyExtractor={item => item.id}
key={Math.random(1000)} {/* No need to have a key attribute on FlatList */}
renderItem={renderItem}
/>
When you add a keyExtractor={item => item.id}, it will search the id on each object of your dataStory, which is undefined in your case, so the key in your case is the same undefined.
So, the first solution is:
Instead of having:
{
type: 'NORMAL',
item: {
id: '1',
image: 'https://picsum.photos/200',
}
}
You should have this:
{
id: '1',
type: 'NORMAL',
item: {
image: 'https://picsum.photos/200',
}
}
The second solution is to change the keyExtractor to be:
keyExtractor={item => item.item.id}
or:
keyExtractor={({item}) => item.id}
im writing a todolist with reactnative using hooks , however when rendering todo items , its not showing up, any advice to fix this
thank you so much for your help!!!
import React, { useState } from 'react';
import { StyleSheet, FlatList, Text, View } from 'react-native';
export default function App() {
const [todos, setTodos] = useState([
{ text: 'budddy', key: '1' },
{ text: 'helloddd', key: '2' },
{ text: "hellddo", key: '3' }
])
return (
<View style={styles.container} >
<View style={styles.content}>
<FlatList data={todos} renderItem={({ item }) => {
<Text> {item.text}</Text>
}} />
</View>
</View>
);
}
const styles = StyleSheet.create({
container: {
paddingTop: 30,
},
content: {
padding: 40
},
})
Check the renderItem code you need to add return or use the implicit return of arrow function
<FlatList data={todos} renderItem={({ item }) => (
<Text> {item.text}</Text>
)} />
Use the extraData property on your FlatList component.
As per documentation:
Bypassing extraData={this.state} to FlatList we make sure FlatList will re-render itself when the state.selected changes. Without setting this prop, FlatList would not know it needs to re-render any items because it is also a PureComponent and the prop comparison will not show any changes.
here is the example code (documentation)
import React from 'react';
import {
SafeAreaView,
TouchableOpacity,
FlatList,
StyleSheet,
Text,
} from 'react-native';
import Constants from 'expo-constants';
const DATA = [
{
id: 'bd7acbea-c1b1-46c2-aed5-3ad53abb28ba',
title: 'First Item',
},
{
id: '3ac68afc-c605-48d3-a4f8-fbd91aa97f63',
title: 'Second Item',
},
{
id: '58694a0f-3da1-471f-bd96-145571e29d72',
title: 'Third Item',
},
];
function Item({ id, title, selected, onSelect }) {
return (
<TouchableOpacity
onPress={() => onSelect(id)}
style={[
styles.item,
{ backgroundColor: selected ? '#6e3b6e' : '#f9c2ff' },
]}
>
<Text style={styles.title}>{title}</Text>
</TouchableOpacity>
);
}
export default function App() {
const [selected, setSelected] = React.useState(new Map());
const onSelect = React.useCallback(
id => {
const newSelected = new Map(selected);
newSelected.set(id, !selected.get(id));
setSelected(newSelected);
},
[selected],
);
return (
<SafeAreaView style={styles.container}>
<FlatList
data={DATA}
renderItem={({ item }) => (
<Item
id={item.id}
title={item.title}
selected={!!selected.get(item.id)}
onSelect={onSelect}
/>
)}
keyExtractor={item => item.id}
extraData={selected}
/>
</SafeAreaView>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
marginTop: Constants.statusBarHeight,
},
item: {
backgroundColor: '#f9c2ff',
padding: 20,
marginVertical: 8,
marginHorizontal: 16,
},
title: {
fontSize: 32,
},
});
I'm new to react-native and am trying to use the Redux framework, I've encountered this problem: (The component for route ' ' must be a React component):
Thank you in advance.
Screen Error
Index.js
import React from 'react'
import { Provider } from 'react-redux'
import { AppRegistry } from 'react-native';
import { name as appName } from './app.json';
import Menu from './app/componnts/Menu'
import storeConfig from './app/store/storeConfig'
const store = storeConfig()
const Redux = () => {
return (
<Provider store={store}>
<Menu />
</Provider>
)
}
AppRegistry.registerComponent(appName, () => Redux);
Menu.js
import React, { Component } from 'react'
import {
StyleSheet,
SafeAreaView,
ScrollView,
Dimensions,
View,
Image,
Text
} from 'react-native'
import { createDrawerNavigator, DrawerItems, } from 'react-navigation'
import Login from './Login/Login'
import Viatura from './Viatura/Viatura'
export default class App extends Component {
render() {
return (
<AppDrawerNavigator />
)
}
}
const CustomDrawerComponent = (props) => (
<SafeAreaView style={{ flex: 1 }}>
<ScrollView>
<DrawerItems {...props} />
</ScrollView>
</SafeAreaView>
)
const AppDrawerNavigator = createDrawerNavigator({
Login,
Viatura,
}, {
contentComponent: CustomDrawerComponent,
drawerWidth: 300,
contentOptions: {
activeTintColor: 'orange'
}
})
Login.js
import React, { Component } from 'react'
import { connect } from 'react-redux'
import { loginStore } from '../../store/actions/user.js';
import { Text, View, ImageBackground, Dimensions, Image, TextInput, TouchableOpacity, Alert } from 'react-native'
import Icon from 'react-native-vector-icons/FontAwesome'
import axios from 'axios'
import { createIconSetFromIcoMoon } from 'react-native-vector-icons'
import { API_MOTORISTAS_LOGIN } from '../../config'
import icoMoonConfig from '../../resources/fonts/selection.json'
import styles from './styles'
import bgImage from '../../images/fundo-vertical-preto.jpg'
import logo from '../../images/logo-tg-v-01.png'
const MyIcon = createIconSetFromIcoMoon(icoMoonConfig, 'icomoon', 'icomoon.ttf');
class Login extends Component {
constructor(props) {
super(props)
this.state = {
user: '',
password: '',
}
this.loginUser = this.loginUser.bind(this)
}
loginUser = () => {
try {
const { user, password } = this.state
this.setState({ error: '', })
axios.post(`${API_MOTORISTAS_LOGIN}`,
{
'param1': this.state.user,
'param2': this.state.password
}, {
"headers": {
'Content-Type': 'application/json',
}
}).then((response) => {
if (response.data.error) {
Alert.alert((response.data.error));
} else {
this.props.onLogin({ ...this.state })
const api_token = response.data.api_token
this.props.navigation.navigate('Viatura', {
api_token: api_token,
})
}
})
.catch((error) => {
console.log("axios error:", error);
});
} catch (err) {
Alert.alert((err))
}
}
static navigationOptions = {
drawerIcon: ({ tintColor }) => (
<MyIcon name="fonte-tg-33" style={{ fontSize: 24, color: tintColor }} />
)
}
render() {
return (
<ImageBackground
source={bgImage}
style={styles.backgroundContainer}>
<View
style={{
height: (Dimensions.get('window').height / 10) * 10,
alignItems: 'center',
justifyContent: 'center',
}}>
<View style={styles.logoContainer}>
<Image source={logo} style={styles.logo} />
</View>
<View style={styles.inputText}>
<View style={styles.iconContainer}>
<MyIcon style={styles.icon} name="fonte-tg-39" size={25} />
</View>
<TextInput
style={styles.input}
placeholder={'User'}
placeholderTextColor={'rgba(0, 0, 0, 0.6)'}
underlineColorAndroid='transparent'
value={this.state.user}
onChangeText={user => this.setState({ user })}
/>
</View>
<View style={styles.inputText}>
<View style={styles.iconContainer}>
<MyIcon style={styles.icon} name="fonte-tg-73" size={25} />
</View>
<TextInput
style={styles.input}
placeholder={'Password'}
secureTextEntry={true}
placeholderTextColor={'rgba(0, 0, 0, 0.6)'}
underlineColorAndroid='transparent'
value={this.state.password}
onChangeText={password => this.setState({ password })}
/>
</View>
<View style={styles.buttonsLogin}>
<TouchableOpacity style={styles.btnSair}>
<Text style={styles.text}> Sair </Text>
</TouchableOpacity>
<TouchableOpacity onPress={this.loginUser} style={styles.btnEntrar}>
<Text style={styles.text}> Entrar </Text>
</TouchableOpacity>
</View>
</View>
</ImageBackground>
)
}
}
const mapDispatchToProps = dispatch => {
return {
onLogin: user => dispatch(loginStore(user))
}
}
export default connect(null, mapDispatchToProps)(Login);
actionTypes.js
export const USER_LOGGED_IN = 'USER_LOGGED_IN';
export const USER_LOGGED_OUT = 'USER_LOGGED_OUT';
user.js (inside actions folder)
import { USER_LOGGED_IN, USER_LOGGED_OUT } from './actionTypes'
export const login = user => {
return {
type: USER_LOGGED_IN,
payload: user
}
}
export const logout = () => {
return {
type: USER_LOGGED_OUT,
}
}
user.js (inside reducers folder)
import { USER_LOGGED_IN, USER_LOGGED_OUT } from '../actions/actionTypes'
const initalState = {
user: null,
password: null
}
const reducer = (state = initalState, action) => {
switch (action.type) {
case USER_LOGGED_IN:
return {
...state,
user: action.paypload.user,
password: action.paypload.password
}
case USER_LOGGED_OUT:
return {
...state,
user: null,
password: null,
}
default:
return state
}
}
export default reducer
storeConfig.js
import { createStore, combineReducers } from 'redux'
import userReducer from './reducers/user'
const reducers = combineReducers({
user: userReducer,
})
const storeConfig = () => {
return createStore(reducers)
}
export default storeConfig
As I said at the beginning of the post, I'm still a beginner at react-native, so I'm posting several snippets of code so that I can be as clear as possible about how my situation is.
I don't think your screen is properly setting export default.
can you change this code?
import React, { Component } from 'react'
import {
StyleSheet,
SafeAreaView,
ScrollView,
Dimensions,
View,
Image,
Text
} from 'react-native'
import { createDrawerNavigator, DrawerItems, } from 'react-navigation'
import Login from './Login/Login'
import Viatura from './Viatura/Viatura'
export default class App extends Component {
render() {
return (
<AppDrawerNavigator />
)
}
}
const CustomDrawerComponent = (props) => (
<SafeAreaView style={{ flex: 1 }}>
<ScrollView>
<DrawerItems {...props} />
</ScrollView>
</SafeAreaView>
)
const AppDrawerNavigator = createDrawerNavigator(
{
Login : () => <Login />,
Viatura : () => <Viatura />
},
{
contentComponent: CustomDrawerComponent,
drawerWidth: 300,
contentOptions: {
activeTintColor: 'orange'
}
}
)
OR
import { Login } from './Login/Login'
import { Viatura } from './Viatura/Viatura'
...
const AppDrawerNavigator = createDrawerNavigator(
{
Login : { screen: Login },
Viatura : { screen: Viatura }
},
{
contentComponent: CustomDrawerComponent,
drawerWidth: 300,
contentOptions: {
activeTintColor: 'orange'
}
}
)
Try this
const AppDrawerNavigator = createDrawerNavigator({
Login:Login,
Viatura:Login,
}, {
contentComponent: CustomDrawerComponent,
drawerWidth: 300,
contentOptions: {
activeTintColor: 'orange'
}
})
red error screen 1
Cannot read property 'configureProps' of undefined
I was using the react-tab-view with react Hooks and typescript but I have some issues somebody could give me a hand...
import React, { useState } from 'react';
import { View, Text, TouchableOpacity, StyleSheet, Dimensions } from 'reactnative';
import { TabView, SceneMap } from 'react-native-tab-view';
const FirstRoute = () => (
<View style={[styles.scene, { backgroundColor: '#ff4081' }]} />
);
const SecondRoute = () => (
<View style={[styles.scene, { backgroundColor: '#673ab7' }]} />
);
interface Props {
navigation: any;
}
export default function Home(props: Props) {
const [rar, setRar] = useState({
index: 0,
routes: [
{ key: 'first', title: 'First' },
{ key: 'second', title: 'Second' },
]
});
var NativeAppEventEmitter = require('RCTNativeAppEventEmitter');
return (
<View>
<TouchableOpacity onPress={props.navigation.openDrawer}>
<Text>hola desde home</Text>
</TouchableOpacity>
<TabView
navigationState={rar}
renderScene={SceneMap({
first: FirstRoute,
second: SecondRoute,
})}
onIndexChange={index => ({ index })}
initialLayout={{ width: Dimensions.get('window').width, height: 250 }}
/>
</View>
)
}
const styles = StyleSheet.create({
scene: {
flex: 0.3,
},
});
change
onIndexChange={index => ({ index })}
to
onIndexChange={index => setRar({ ...rar, index })}
that should fix the error you are facing
import React, { useState, useEffect } from 'react';
import { Container } from './styles';
import { View, StyleSheet, Dimensions } from 'react-native';
import { TabView, SceneMap } from 'react-native-tab-view';
const LatestRoute = () => (
<View style={[styles.scene, { backgroundColor: '#ff4081' }]} />
);
const FavoritesRoute = () => (
<View style={[styles.scene, { backgroundColor: '#673ab7' }]} />
);
const AllRoute = () => (
<View style={[styles.scene, { backgroundColor: '#673ab7' }]} />
);
const styles = StyleSheet.create({
scene: {
flex: 1,
},
});
export default function Main() {
const initialState = {
index: 0,
routes: [
{ key: 'latest', title: 'Latest' },
{ key: 'favorites', title: 'Favorites' },
{ key: 'all', title: 'All' },
],
};
const [ state, setState ] = useState(initialState);
function selectTab ( index ) {
this.initialState = {
index: index,
routes: [
{ key: 'latest', title: 'Latest' },
{ key: 'favorites', title: 'Favorites' },
{ key: 'all', title: 'All' },
],
};
return setState(this.initialState);
}
return (
<Container>
<TabView
navigationState={state}
renderScene={SceneMap({ latest: LatestRoute, favorites: FavoritesRoute, all: AllRoute })}
onIndexChange={ (index) => selectTab(index) }
initialLayout={{ width: Dimensions.get('window').width, height : Dimensions.get('window').height }}
/>
</Container>
);
}
How can I close SwipeRow inside FlatList?
This is the easy thing to do with ListView, but since the next release is going to use FlatList it should be possible.
From reading their source code, it seems like it is not implemented yet.
can you try this
import React, { Component } from 'react';
import { FlatList } from 'react-native';
import { Container, Header, Content, SwipeRow, View, Text, Icon, Button } from 'native-base';
export default class App extends Component {
constructor(props) {
super(props)
this.state = { data: [{ key: 'a' }, { key: 'b' }] }
this.component = [];
this.selectedRow;
}
render() {
return (
<Container>
<Header />
<Content>
<FlatList
data={[{ key: 'a', value: 'Row one' }, { key: 'b', value: 'Row two' }, { key: 'c', value: 'Row three' }, { key: 'd', value: 'Row four' }, { key: 'e', value: 'Row five' }]}
keyExtractor={(item) => item.key}
renderItem={({ item }) => <SwipeRow
ref={(c) => { this.component[item.key] = c }}
leftOpenValue={75}
rightOpenValue={-75}
onRowOpen={() => {
if (this.selectedRow && this.selectedRow !== this.component[item.key]) { this.selectedRow._root.closeRow(); }
this.selectedRow = this.component[item.key]
}}
left={
<Button success onPress={() => alert('Add')}>
<Icon active name="add" />
</Button>
}
body={
<View style={{ paddingLeft: 20 }}>
<Text>{item.value}</Text>
</View>
}
right={
<Button danger onPress={() => alert('Delete')}>
<Icon active name="trash" />
</Button>
}
/>}
/>
<Button style={{ margin: 20 }} onPress={() => this.selectedRow._root.closeRow()}><Text>Close row</Text></Button>
</Content>
</Container>
);
}
}