Step 3
We need to build a (web) server, with NodeJS/Express for instance, to handle routing requests for different endpoints;
when a user visits /create
we must response with the HTML file (and associated styling/script files) for "create meeting" view.
In React apps, we can get away by using third-party libraries for routing. A popular choice is react-router which provides a collection of navigational components for React applications.
Stop your application and install react-router and the related package react-router-dom:
npm install react-router react-router-dom
Working with react-router is relatively simple!
Open index.js
and import the BrowserRouter
from the react-router
package:
import { BrowserRouter as Router } from "react-router-dom";
Now wrap the App
component:
ReactDOM.render(
<Router>
<App />
</Router>,
document.getElementById("root")
);
Next, open App.js
and import the BrowserRouter
from the react-router
package:
import { Route, Switch } from "react-router";
Update the render
method of App
component:
render() {
return (
<Switch>
<Route exact path="/">
<ListMeetings
meetings={this.state.meetings}
onDeleteMeeting={this.removeMeeting}
/>
</Route>
<Route path="/create">
<CreateMeeting />
</Route>
</Switch>
);
}
Save the file and run the application. Open http://localhost:3000 to view it in the browser. Click on the add icon to navigate to the "create meeting" view and click on the back button to return to the homepage.
The
react-router
library manipulates and makes use of browser's session history to provide a sense of routing!
Libraries like react-router
are "hacking" routing! In my experience, there are many problems with this approach ranging from when you deploy your application to a service like GitHub Pages (where the base URL is not the domain) to issues with revisiting a page after you have updated its state from another view.
There are alternatives to react-router
and you can build your own too. I recommend the following readings if you are interested to learn more: