1

I want to click a button and i navigate to the next page belwo is my button:

<RaisedButton label="Sign In"
           style={style}
           labelColor="#fff"
           onClick={this.navigateToHome}
           backgroundColor="#20B2AA" /> 

and this is how i set the onClick Method to route to the next page but it's not working :

 navigateToHome = () => {
    <Router>
      <Route  path={"/HomePage"} component={HomeActivity}/>
    </Router>
  };

My full class:

import React from 'react';
import './App.css';
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';
import {Card,CardHeader,CardText} from 'material-ui/Card';
import FlatButton from 'material-ui/FlatButton';
import TextField from 'material-ui/TextField';
import RaisedButton from 'material-ui/RaisedButton';
import {Router,Route} from 'react-router'
import {HomeActivity} from './HomeActivity'

const style = {
  margin: 12,
};
export class LoginCardView extends React.Component{


  navigateToHome = () => {
    <Router>
      <Route  path={"/HomePage"} component={HomeActivity}/>
    </Router>
  };

  render()
  {
  return(
    <center>
        <MuiThemeProvider>
    <Card  className="CardLogin" >

  <CardText>
    <div >
     <h4 className="TextLoginCenter"> Sign In</h4>

      <tr>
        <td> <TextField
      hintText="Enter Username"
    /></td>
      </tr>
      <tr>
        <td> <TextField
      hintText="Enter Password"
       type="password"
    /> </td>
      </tr>

      <tr>
        <td>  <RaisedButton label="Sign In"
           style={style}
           labelColor="#fff"
           onClick={this.navigateToHome}
           backgroundColor="#20B2AA" />  </td>
      </tr>

    </div>
      </CardText>

    </Card>
  </MuiThemeProvider>
</center>
         );
  }
}

1 Answers1

0

You must use withRouter() and this.props.router.push().

import {Router,Route,withRouter} from 'react-router';


class LoginCardView extends React.Component{
  constructor(props){
    //...
    this.navigateToHome = this.navigateToHome.bind(this);
    //...
    //...
  }
  ...
  navigateToHome(){
    this.props.router.push("/HomePage");
  };
  //...
  //...
  //...
export default withRouter(LoginCardView)
Emad Emami
  • 6,089
  • 3
  • 28
  • 38
  • am getting this error `TypeError: Cannot read property 'push' of undefined LoginCardView._this.navigateToHome`, when i press the button –  Nov 09 '17 at 08:53
  • yes i did , but also the class has export –  Nov 09 '17 at 09:13
  • Am now getting this when i remove export on top and i put only bottom `./src/App.js 67:30-43 './LoginCardView' does not contain an export named 'LoginCardView'.` –  Nov 09 '17 at 09:19
  • 1
    The version is **"react-router": "^4.2.0"** –  Nov 09 '17 at 09:26
  • are you using another HOC in this component? something like `connect` or ... ? if yes try this: https://stackoverflow.com/a/37024305/2357848 – Emad Emami Nov 09 '17 at 09:31