ReactJS Navigation

You do it with react router. Here is the react router tutorial.

Your list of users is the first page which is shown when you open the site, thus that is your index page and all other pages are routes.

Thus 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 your 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'));

Here you wrap it under Router which comes from react-router, and there you pass history prop which you want to use and routes prop. You can use browserHistory and hashHistory. BrowserHistory shows cleaner urls. With hash history you have something like someurl.com/#/something

Now in your app you can do next :

export default class App extends Component {
    render() {

        return (
           <div>
              {this.props.children}
           </div>
        );
    }
}

{this.props.children} renders all routes from routes file, because you have specified App component for the main route.

On the add user button onClick event you can navigate to the add user form with browserHistory, thus :

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 button click on add user form, the same process, you only need to navigate to the index route with "/", thus :

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.

Tags:

Reactjs