user2194838 user2194838 - 2 months ago 7
React JSX Question

Navigation from component to another componet

I have login component and dashboard. My application entry point is login page. After successful login, I want move to main page(dashboard & navigation).

I tried this like the following but its not working. After login not able to move to dashboard.

My login Component is

var React = require('react');
var {Link} = require('react-router');
var Dashboard = require('Dashboard');

var Login = React.createClass ({
onFormSubmit: function(e){
e.preventDefault();
<Dashboard />
},
render: function(){
return (
<div>
<h1 className="text-center">Login</h1>
<form onSubmit={this.onFormSubmit}>
<input type="text" ref="username"/>

<button className="button">Login</button>
</form>
</div>
)
}
});

module.exports = Login;


My Dashboard component is

var React = require('react');
var Nav = require('Nav');

var Dashboard = (props) => {
return (
<div>
<Nav/>
<div className="row">
<div className="columns medium-6 large-4 small-centered">
{props.children}
</div>
</div>
</div>
);
}

module.exports = Dashboard;


Main app.jsx file is

var React = require('react');
var ReactDOM = require('react-dom');
var {Route, Router, IndexRoute, hashHistory} = require('react-router');
var Login = require('Login');
var Dashboard = require('Dashboard');
var About = require('About');
var Examples = require('Examples');

ReactDOM.render(
<Router history={hashHistory}>
<Route path="/" component={Login}>
<Route component={Dashboard}>
<Route path="about" component={About}/>
<Route path="examples" component={Examples}/>
</Route>
</Route>
</Router>,
document.getElementById('app')
);

Answer

Your onFormSumit() should be like this

onFormSubmit: function(e){
    e.preventDefault();
   window.location.href = '/dashboard'
},

And your <Router/> in app.jsx should be like this

<Router history={hashHistory}>
   <Route path="/" component={Login} />
   <Route path="dashboard" component={Dashboard} />
   <Route path="about" component={About}/>
   <Route path="examples" component={Examples}/>
 </Router>

This will make the browser redirect to /dashboard on form submit. That redirected url(/dashboard) will be captured by the <Router/> and the component for that path will be rendered.

[Update]

In your express, you nee to add the path so that it always returns the index.html page. Add this

app.get(['/', '/dashboard'], function(req, res){
  res.sendfile('./path to your index.html file')
})

or you can do the following also

app.get('*', function(req, res){
   res.sendfile('./path to your index.html file')
})

For further read, check this