I am new to React, and I am having an issue redirecting to a new page using JavaScript event handlers. I don't know what I am not getting right.
import React, { Component } from 'react';
import {Switch, Route} from 'react-router-dom';
import Nav, {Jumbotron} from '../partials/headobjs';
import Footer from '../partials/footer';
import Users from '../components/user';
import UserObj from '../components/userobj';
import Err404 from '../components/err404';
//import css files..
import '../css/styles.css';
class App extends Component {
render() {
return (
<div>
<Nav />
<Jumbotron/>
<Switch>
<Route exact path='/' component={Users}/>
<Route path='/user' component={UserObj}/>
<Route component={Err404} />
</Switch>
<div className='clr'></div>
<Footer />
</div>
);
}
}
export default App;
import React, { Component } from 'react';
import {Redirect} from 'react-router-dom';
class Users extends Component {
constructor(){
super();
this.state = {
name:aminu
};
}
gotoURL(usr){
let url = `/user/${usr}`;
//console.log(url);
return <Redirect to={url}/>
}
render() {
return (
<div className="container">
<button onClick={this.gotoURL.bind(this, this.state.name)}>
Go to {this.state.name} page
</button>
</div>
);
}
}
export default Users;
I want the function gotoURL to redirect to a new route, but I'm not sure what I am doing wrong, I have tried using the browserHistory, and now I'm trying out the <Redirect/> class but yet to no avail.
Redirect component needs to be rendered and not returned to the onClick handler which is why it is not working. You can make use of history.push instead
gotoURL(usr){
let url = `/user/${usr}`;
//console.log(url);
this.props.history.push(url);
}
Instead of redirect from function, use render method and state to workout with redirect problem
class Users extends Component {
constructor(){
super();
this.state = {
name:'aminu',
toUser: false
};
}
gotoURL(usr){
let url = `/user/${usr}`;
//console.log(url);
this.setState({toUser:true, goto: url})
}
render() {
if (this.state.toUser === true) {
return <Redirect to={this.state.goto}/>
}
return (
<div className="container">
<button onClick={this.gotoURL.bind(this, this.state.name)}>
Go to {this.state.name} page
</button>
</div>
);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With