I am in the very initial stages of trying to build out an app, and am a React-Native novice. I am getting the following navigation error: undefined is not an object (evaluating 'this.props.navigation.navigate')
.
What I have tried:
I've read the answers to this question and this one. I understand that the problem is that I am not passing down navigation as props correctly to my component. I just don't quite know how to fix that. I tried to ensure that all my components were screens in the main App.js file. I'm sure I'm not doing it right, but I'm unsure of the right way to do it.
Here is my main App.js so far:
import React from 'react';
import { StyleSheet, Text, View } from 'react-native';
import * as firebase from "firebase";
import TodoList from './components/TodoList'
import AddTask from './components/AddTask'
import { StackNavigator } from 'react-navigation'
// Initialize Firebase
var config = {
apiKey: "<api-key>",
authDomain: "<auth-domain>",
databaseURL: "<databaseURL>",
storageBucket: "<storageBucket>"
};
firebase.initializeApp(config);
export default class Home extends React.Component {
constructor(props) {
super(props)
this.state = {todos: []}
}
componentDidMount() {
firebase.database().ref('/tasks').on('value', data => {
console.log(data.val())
this.setState({ todos: (data.val()) })
})
}
render() {
return (
<View style={styles.container}>
<TodoList database={database} todos={this.state.todos} />
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
},
});
const App = StackNavigator({
Home: { screen: Home },
TodoList: { screen: TodoList },
AddTask: { screen: AddTask }
});
The TodoList component:
import React from 'react';
import { StyleSheet, Text, View, FlatList, Button } from 'react-native';
import * as firebase from "firebase";
import AddTask from './AddTask'
import { StackNavigator } from 'react-navigation'
export default class TodoList extends React.Component {
constructor(props) {
super(props)
this.state = {
todos: [],
database: this.props.database
}
}
static navigationOptions = {
title: 'To Do List',
};
_keyExtractor = (item) => item.name
render() {
const { navigate } = this.props.navigation;
return (
<View style={styles.container}>
<FlatList
data={this.props.todos}
keyExtractor={this._keyExtractor}
renderItem={({ item }) => <Text style={styles.item}>{item.name}</Text>}
/>
<Button
onPress={() =>
navigate('AddTask')
}
title="Add a Task"
color="#841584"
/>
</View>
)
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
paddingTop: 22
},
item: {
padding: 10,
fontSize: 18,
height: 44,
},
})
The AddTask component thus far:
import React from 'react';
export default class AddTask extends React.Component {
static navigationOptions = {
title: 'Add a Task',
};
render() {
return (
<View>
<Text>This is the Add Task Page</Text>
</View>
);
}
}
Thanks in advance for your help.