npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@axtk/react-router

v2.0.0

Published

A lightweight React router

Downloads

39

Readme

npm GitHub browser SSR TypeScript

@axtk/react-router

Core ideas:

  • Route matching might look like conditional rendering (to be easily applicable to both components and props).
  • The route link component might have the same props as an ordinary HTML link (to be easily convertable and immediately familiar).
  • There might be a hook to convert plain HTML links to route links.
  • Server-side rendering (SSR) might not require a substantially different router setup.

Usage

// App.jsx
import {useRoute, A} from '@axtk/react-router';
// `A` is a link component enabling navigation without page reloading.
// (To comply with the History API, it won't require page reloads as
// long as the `href` prop value is a same-origin location. With
// non-same-origin URLs, `A` will act as a plain HTML link.)

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

export default const App = () => {
    // The `useRoute` hook enables the component's updates in response
    // to URL changes.
    const [route, withRoute] = useRoute();
    // `route` is a utility object providing a `window.location`-like
    //    API for the interaction with the app's route and allowing
    //    for subscription to URL path changes.
    // `withRoute(routePattern, x, y)` is a function acting somewhat
    //    similar to the ternary operator (`?:`); it returns `x` if
    //    `routePattern` matches the current route and `y` otherwise.
    //    `x` and `y` can also be functions of `({path, params})` with
    //    `params` containing the values of the capturing groups (both
    //    named and unnamed) if `routePattern` is a regular expression.

    return (
        <div className="app">
            <div className="navbar">
                <A href={AppRoute.HOME}
                    className={withRoute(AppRoute.HOME, 'active')}>
                    Home
                </A>
                {' | '}
                <A href={AppRoute.INTRO}
                    className={withRoute(AppRoute.INTRO, 'active')}>
                    Intro
                </A>
            </div>
            <div className="main">
                {withRoute(AppRoute.HOME, (
                    <div className="section" 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>
                    </div>
                ))}
                {withRoute(AppRoute.INTRO, (
                    <div className="section" id="intro">
                        <h1>Intro</h1>
                    </div>
                ))}
                {withRoute(AppRoute.SECTION, ({params}) => (
                    <div className="section">
                        <h1>Section #{params.id}</h1>
                    </div>
                ))}
                {withRoute(allKnownRoutes, null, (
                    <div className="error section">
                        <h1>404 Not found</h1>
                    </div>
                ))}
                <div className="footer">
                    <hr/>
                    <button onClick={() => {
                        // `route` can be handy where `<A>` and
                        // `withRoute` are not applicable
                        route.assign(AppRoute.HOME);
                    }}>
                        Home
                    </button>
                </div>
            </div>
        </div>
    );
};
// index.js
import ReactDOM from 'react-dom';
import App from './App';

ReactDOM.render(<App/>, document.querySelector('#root'));

Generally, route returned from the useRoute hook is 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. Therefore, a wrapping <Router> can only be useful to provide a custom route prop value (which is either a string location or a Route class instance).

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) => {
    const html = ReactDOMServer.renderToString(
        <Router route={req.originalUrl}><App/></Router>
    );

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

Converting plain links

In some cases, it can be necessary to convert plain HTML links to SPA route links (that is to make them navigable without page reloading), where the route link component (shown in the example above) is not applicable right away. For instance:

  • if the plain links are part of a server-fetched chunk of content, or
  • if the plain links are part of a fixed internationalization string, or
  • if the plain links have already been used in many parts of the application.

In these cases, the useRouteLinks hook can be helpful.

// With this hook, the plain links matching the selector will become
// navigable without page reloading.
useRouteLinks(componentRef, '.content a');
// `componentRef` is a value returned from the React's `useRef` hook.

Also