DEV Community

Kelp
Kelp

Posted on • Updated on

Build a React SPA without Redux.

We need two elements to render a page on the client.

  • Template. The React component.
  • Data. We fetch data from the backend.

The client-side app fetch data from the backend, then render it on the browser DOM.
It is really simple work. But what we do on projects. We use flux, redux, redux-thunk, redux-saga...

I have used redux, but I think redux takes too much time to build actions and reducers.
We just want a client-side router. We define the page of routes with the component and that how to fetch data.

I build capybara router. It is a react router without flux and redux.
It provides a simple way to build a frontend app of SPA.

GitHub logo kelp404 / capybara-router

Unfancy react router without flux and redux.

capybara-router

npm version Coverage Status Actions Status

This is a react router without flux and redux.
We just want a simple way to build a Single Page Application.
Define rules that include the component and how to fetch data of the each page in a router.

Installation

npm install capybara-router --save
Enter fullscreen mode Exit fullscreen mode

Live demo

https://kelp404.github.io/capybara-router/

Example

/example

const React = require('react');
const ReactDOM = require('react-dom');
const {Router, RouterView} = require('capybara-router');
const history = require('history');
const axios = require('axios');
const ErrorPage = props => {
  return <h2 className="text-center">{`${props.error}`}</h2>;
};
const Home = props => {
  console.log(props.data);
  return <h2>Home</h2>;
};
Enter fullscreen mode Exit fullscreen mode

Live demo of SPA with capybara router.

Simple example code of building SPA with capybara router.

const React = require('react');
const ReactDOM = require('react-dom');
const {Router, RouterView} = require('capybara-router');
const history = require('history');
const axios = require('axios');

const ErrorPage = props => {
  return <h2 className="text-center">{`${this.props.error}`}</h2>;
};
const Home = props => {
  return <h2>Home</h2>;
};

const router = new Router({
  history: history.createBrowserHistory(),
  routes: [
    {
      name: 'web',
      uri: '/',
      onEnter: props => {
        document.title = 'Home';
      },
      resolve: {
        data: params => {
          return axios({
            method: 'get',
            url: `/data/${params.id}.json`
          }).then((response) => {
            return response.data;
          });
        }
      },
      component: Home
    }
  ],
  errorComponent: ErrorPage
});
router.start();

const element = (
  <RouterView>
    <p className="text-center text-muted h3" style={padding: '20px 0'}>
      <i className="fa fa-spinner fa-pulse fa-fw"></i> Loading...
    </p>
  </RouterView>
);
ReactDOM.render(
  element,
  document.getElementById('root')
);
Enter fullscreen mode Exit fullscreen mode

more details example

Top comments (0)