Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React: Invoke redirect to page, and pass parameter

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);
...
...
like image 755
hellogoodnight Avatar asked May 01 '16 10:05

hellogoodnight


1 Answers

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 
} 
like image 141
Chris Avatar answered Oct 26 '22 10:10

Chris