React Router Example with ES6 and htaccess


React has been out there for a while and it is becoming one of the most popular frontend frameworks. It allows you to build reusable UI components and makes maintaining changes in your data’s state effortless by abstracting the DOM giving you a simpler programming model and better performance.

React Router

React greatly simplifies developing Single Page Applications (SPA). One of the most critical components of an SPA is the router. React doesn’t come with a router out of the box. I guess that makes sense since it is a Javascript Library for building user interfaces.

I created a sample application using React, React Router and ES6. I’m using webpack to bundle all the scripts into one single file.

Let me explain to you how it works: It’s an ecommerce platform. The homepage lists all the products. By clicking on a product, the URL changes without reloading the page and the page displays the details related to the product. The data shown are static but of course you can do an AJAX request to get data from a database or a RESTful service.

To run the code, you need to have npm installed.

First clone the repo:

Install the project dependencies:

To compile the JSX files and create the bundle, run the following npm command:

What happens when the user reloads the page?

Since the routing is happening using Javascript, the user will get a 404 error and we will lose the browsing state when the user reloads the page. If your server can handle .htaccess files here is what you will need to have in your htaccess file in the root of your application:

When the user refreshes the page, the server will redirect the request to index.html which will handle the URL. You can do that with any server that supports module rewrite (nginx, IIS)

That’s it for toady and be sure to check out my blog for upcoming posts and code snippets.

Leave a Reply

Your email address will not be published. Required fields are marked *