Navigating ReactJS
I am working on a sample responsejs application (in training). I have a page that lists a list of users and an add button to add a new user.
When I click the Add button, I have to navigate to the user form to create a new user.
After I click the Submit button on the user form, it should return to the first page where there should be a list of users along with the new user.
How to navigate between pages in react?
source to share
You do this with a responsive router. Here is a tutorial on how to react to a router .
Your user list is the first page that is displayed when you open the site, that is, this is your index page and all other pages are routes.
So you can do something like this:
You can create a separate file with your routes:
import UserList from 'path/to/user/list';
import AddUserForm from 'path/....';
const routes = (
<Route path="/" component={App}>
<IndexRoute component={UserList}/>
<Route path="addUser" component={AddUserForm}/>
</Route>
);
export default routes;
Then yours index.js
should look something like this:
import React from 'react';
import ReactDOM from 'react-dom';
import {Router, browserHistory} from 'react-router';
import routes from 'path/to/routes';
ReactDOM.render(<Router history={browserHistory} routes={routes}/>, document.getElementById('root'));
This is where you wrap it under Router
which comes from react-router
, and there you skip the history you want to use and route the prop. You can use browserHistory
and hashHistory
. BrowserHistory shows clean URLs. With history of hashes, you have something likesomeurl.com/#/something
Now in your application, you can do the following:
export default class App extends Component {
render() {
return (
<div>
{this.props.children}
</div>
);
}
}
{this.props.children}
displays all routes from the routes file because you specified an App component for the main route.
In the onClick event of the add user button, you can navigate to the add user form with browserHistory, like this:
import { browserHistory } from 'react-router;
.........
onClick(){
browserHistory.push("/addUser");
}
.......
render(){
return (
//Userlist with the button
<button onClick={this.onClick.bind(this)}>Add New user</button>
);
}
And then on clicking the add custom form button, the same process, you only need to go to the index route using "/"
, like this:
import { browserHistory } from 'react-router;
.........
onClick(){
//Your code to add user to the list of users
browserHistory.push("/");
}
.......
render(){
return (
//Add user form
<button onClick={this.onClick.bind(this)}>Add User</button>
);
}
Hope this helps.
source to share