Although backend blood flows through our veins we are not afraid of frontend tasks. We are well experienced in AngluarJS and Angular 4 and we are experimenting with ReactJS whenever we can. Here is one simple ReactJS app that we use to try various ReactJS features. It can be used as a boilerplate code for any project where you need Redux, Router v4 and route redirection, user authentication, AJAX calls, Less, controlled components etc.
This simple application has menu, login form, table that displays objects administrated by this app (we called them “things”) and one form where we can create or edit the “thing”. Any user can see the table of things but only logged in user can create it or edit.
The source code and demo can be found on GitHub. Let’s now explore its features, one by one.
Router
- With Redirect component – explained in this example. We simply keep the Boolean flag in local state or in store whether we need to redirect and where. When we need to redirect we set that flag to true. In render() function we will return <Redirect> component
if (shouldRedirect) { return <Redirect to={route} /> }
For our example check the Login component.
- With history object
this.props.history.push(route);
For our example check the Thing component and its redirectTo() function.
User authentication
- AJAX calls that can be made,
- components that can be rendered or
- action that can be performed
- Keep the user’s data (username) in Redux store
- If user is not logged in and he tries to do something of the above we will redirect him to the login form. At the same time we will save in Redux store the current route so the user can be redirected back to that route after successful login.
In AuthenticatedRoute we check whether the user is logged in or not. If yes, we will render the component. If not we will redirect him to the Login route. For both please check the render() function of the AuthenticatedRoute.
Form
- Check if data is loaded – callback componentDidMount() in Thing component
- Load the data with AJAX call – function loadAllThings() – keep in mind that this is asynchronous call
- Save them in Redux store – dispatch “ADD_THINGS” action
- Take the appropriate Thing object from Redux store and set it in local store – function prepareThingToEdit()
- Render the form
Less to CSS transpiling
{ test: /\.less$/, loaders: ['style-loader', 'css-loader', 'less-loader'] }