Reputation: 23
I am trying to redirect to another router when the user clicks a specified button (named Navigate in this case) in a class-based component (named Counter). I am using <Navigate />
for that. It doesn't redirect to the page I specified to redirect to (path='/' for the homepage). In addition, I don't get any errors. Someone, please tell me the best way to use the <Navigate />
.
For reference, the code is:
import React, {Component} from "react";
import {Navigate} from 'react-router-dom'
class Counter extends Component {
constructor(props){
super(props)
this.state = {
}
this.navigate = this.navigate.bind(this)
}
navigate(e){
return <Navigate to="/" />
}
render(){
return (
<div className='text-center'>
<h1>Hello there, this is a counter app</h1>
<button onClick={this.navigate} >Navigate</button>
</div>
)
}
}
export default Counter
Upvotes: 2
Views: 1753
Reputation: 256
You should try this. In your component navigate function cannot return Navigation. There are other methods for switching routes programmatically. Read this https://reactrouter.com/docs/en/v6/getting-started/concepts
import React, {Component} from "react";
import {Navigate} from 'react-router-dom'
class Counter extends Component {
constructor(props){
super(props)
this.state = {
dashboard: false,
}
this.navigate = this.navigate.bind(this)
}
navigate(e){
this.setState({dashboard:true})
}
render(){
return (
<div className='text-center'>
{this.state.dashboard && (
<Navigate to="/dashboard" replace={true} />
)}
<h1>Hello there, this is a counter app {this.state.dashboard && <span>dashboard</span>}</h1>
<button onClick={this.navigate} >Navigate</button>
</div>
)
}
}
export default Counter
Upvotes: 1