Giter Club home page Giter Club logo

react-keenrouter's Introduction

npm GitHub React SSR TypeScript

react-keenrouter

React router with componentless route matching

Features

  • componentless route matching
    • doesn't enforce route collocation and tight coupling within a route hierarchy;
    • works the same way both for components and dynamic route-based prop values;
    • is akin to the common React pattern of conditional rendering;
  • the history-based route link components <A> and <Area> with the props similar to those of the ordinary HTML link elements <a> and <area> (allowing for quick migration back and forth and working more like a polyfill to ordinary links);
  • the <Router> component fit for both browser and server rendering;
  • the utility converting plain HTML links (that can't be easily replaced with React components) to history-based links.

Example

import {A, useRoute} from 'react-keenrouter';

const appRoutes = {
    HOME: '/',
    INTRO: '/intro',
    SECTION: /^\/section\/(?<id>\d+)\/?$/,
};

const allKnownRoutes = Object.values(appRoutes);

export const App = () => {
    // the `useRoute()` hook subscribes the component to URL changes
    let [route, withRoute] = useRoute();

    return (
        <div className="app">
            <nav>
                {/* the route link component `A` looks similar to the
                    plain HTML link as it serves a similar purpose */}
                <A
                    href={appRoutes.HOME}
                    // `withRoute()` checks the current location and
                    // works similar to the conditional ternary operator;
                    // below, it roughly means:
                    // `home location ? 'active' : undefined`
                    // (the omitted third parameter is `undefined`)
                    className={withRoute(appRoutes.HOME, 'active')}
                >
                    Home
                </A>
                {' | '}
                <A
                    href={appRoutes.INTRO}
                    className={withRoute(appRoutes.INTRO, 'active')}
                >
                    Intro
                </A>
            </nav>
            {withRoute(
                appRoutes.HOME, (
                    <main id="home">
                        <h1>Home</h1>
                        <ul>
                            <li>
                                <A href="/section/1">Section #1</A>
                            </li>
                            <li>
                                <A href="/section/2">Section #2</A>
                            </li>
                        </ul>
                    </main>
                ),
            )}
            {/* although `withRoute()` calls may appear in groups like
                in this example, they work independently from each other
                and may as well be used uncoupled in different places of
                an application */}
            {withRoute(
                appRoutes.INTRO, (
                    <main className="section" id="intro">
                        <h1>Intro</h1>
                    </main>
                ),
            )}
            {/* the second and the third parameter of `withRoute()` can
                be functions of `{href, params}`, with `params`
                containing the capturing groups of the location pattern
                if it is a regular expression */}
            {withRoute(appRoutes.SECTION, ({params}) => (
                <main className="section">
                    <h1>Section #{params.id}</h1>
                </main>
            ))}
            {/* below, rendering `null` if the current location
                matches `allKnownRoutes`, and the 404 error screen
                otherwise */}
            {withRoute(
                allKnownRoutes,
                null, (
                    <main className="error section">
                        <h1>404 Not found</h1>
                    </main>
                ),
            )}
            <footer>
                <hr/>
                <button
                    onClick={() => {
                    // `route` has a `window.location`-like API and can
                    // be handy for direct manipulation of the location
                        route.assign(appRoutes.HOME);
                    }}
                >
                    Home
                </button>
            </footer>
        </div>
    );
};
import {createRoot} from 'react-dom/client';
import {App} from './App';

createRoot(document.querySelector('#app')).render(<App/>);

The route object returned from the useRoute() hook is an instance of the NavigationLocation class provided by the wrapping <Router> component. If there is no <Router> up the React node tree (like with <App/> in the example above), a default route based on the current page location is used. A wrapping <Router> can be useful to provide a custom route prop value that accepts either a string location or a NavigationLocation class instance.

Custom routing

The default route object returned from the useRoute() hook responds to changes in the entire URL, with pathname, search, and hash combined. This can be changed by providing an instance of a customized extension of the NavigationLocation class to the Router component.

import {NavigationLocation} from 'react-keenrouter';

export class PathLocation extends NavigationLocation {
    deriveHref(location) {
        // disregarding `search` and `hash`
        return getPath(location, {search: false, hash: false});
    }
}
import {createRoot} from 'react-dom/client';
import {Router} from 'react-keenrouter';
import {PathLocation} from './PathLocation';

createRoot(document.querySelector('#app')).render(
    <Router route={new PathLocation()}>
        <App/>
    </Router>,
);

Extending the NavigationLocation class gives plenty of room for customization. This approach allows in fact to go beyond the URL-based routing altogether.

Server-side rendering (SSR)

For the initial render on the server, the <Router> component can be used to pass the current route location to the application in essentially the same way as it can be done in the client-side code:

// On the Express server
app.get('/', (req, res) => {
    let html = ReactDOMServer.renderToString(
        <Router route={req.originalUrl}><App/></Router>,
    );

    // Sending the resulting HTML to the client.
});

Converting plain links

The useRouteLinks() hook can be helpful when it's necessary to convert plain HTML links to SPA route links if the route link component is not applicable right away (for instance, in a server-fetched static chunk of HTML content):

useRouteLinks(containerRef, '.content a');
// `containerRef` is a value returned from the React's `useRef()` hook.

react-keenrouter's People

Contributors

axtk avatar

Stargazers

Abdulgafur avatar

Watchers

James Cloos avatar  avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.