Reputation: 15
I have Login.js and List.js in 'pages' folder while Form.js in 'component' folder. Form.js is a child component of Login.js . When I want to navigate from Login.js to List.js I simply use onPress={() => this.props.navigation.navigate('List')
but if I use this same code in Form.js it says: Undefined is not an object (evaluating '_this2.props.navigation.navigate')
Upvotes: 1
Views: 73
Reputation: 304
You can pass a function from Login to Form to execute that function from Login
Function Component form
const Login = props => {
const goToList = () => {
this.props.navigation.navigate('List')
}
return (
<Form redirectList={goToList} />
)
}
const Form = props => {
props.redirectList() // This will execute the navigate from Login component
}
Class Component form
class Login extends React.Component {
constructor(props){
super();
this.goToList = function(){
this.props.navigation.navigate('List')
}
}
render(){
return (
<Form redirectList={this.goToList} />
)
}
}
class Form extends React.Component {
constructor(props){
super();
this.redirectToList = function(){
props.redirectList();
}
}
// You can redirect to list using
this.redirectToList();
}
Upvotes: 1
Reputation: 246
I can't see your code so I can't tell that this is exactly what you are looking for, but try something like this:
import React from 'react'
import { withRouter } from 'react-router-dom'
export function Form() {
const ListBtn = withRouter(({ history }) => (
<button onClick={() => {history.push('/list')}}>
Go to list
</button>
))
return (
<ListBtn />
)
}
Upvotes: 1