Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
145
rated 0 times [  147] [ 2]  / answers: 1 / hits: 17683  / 8 Years ago, sun, may 1, 2016, 12:00:00

I am building my first React app.
In my code, I redirect to another page (a component) using



browserHistory.push(pathToMyComponent)


I also have tried out the react-router Link-element. The Link element enables me to pass data to the target component without having it showing up in the URL, like this:



<Link to={`/myComponent/${someData}`}>


But now I don't want to create a link. Instead I want to perform some operations when pushing a button, and then redirect with some calculated data.
How do I do this?



Edit:
Here is my code. In loginpage, the user can perform a facebook login. What I want is to redirect the user to the lobby after login succeeded. I want to pass the userid to the lobby.



<Router history={browserHistory} onUpdate={() => window.scrollTo(0, 0)}>
<Route path=/ component={LoginPage}/>
<Route path=/lobby component={Lobby}/>
</Router>


This is what I wrote after reading your answer. When this is executed, the log prints Uncaught TypeError: Cannot read property 'context' of null



this.context.router.push({ //browserHistory.push should also work here
pathname: '/lobby',
state: {userid: authData.uid}
});


Edit2: You mean like this? It gives syntax error.



class LoginPage extends React.Component {

contextTypes = {
router: React.PropTypes.object
};
constructor(props){
super(props);
...
...

More From » reactjs

 Answers
55

I would create a normal button with an onClick event handler which would fire a function. In this function you can calculate the data that you want and then finally do a push to your router.



Example:



render() {
return (
...
<button onClick={this._handleButtonClick}>Click me</button>
...
);
}

_handleButtonClick = () => {
//calculate your data here
//then redirect:
this.context.router.push({ //browserHistory.push should also work here
pathname: pathToMyComponent,
state: {yourCalculatedData: data}
});
}


You'll then be able to get that data from your location's state.



Check out the docs for this here.



EDIT:



To use this.context.router add this inside your components' class:



static contextTypes = { 
router: React.PropTypes.object
}

[#62339] Thursday, April 28, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
destanyb

Total Points: 407
Total Questions: 88
Total Answers: 88

Location: Senegal
Member since Mon, Sep 5, 2022
2 Years ago
;