Code Monkey home page Code Monkey logo

hookrouter's Introduction

React Hook Router

A different approach to utilize a routing functionality in react. I am using this router in an application which is running in production right now without any errors so far. Until I found the time to write some real unit/integration tests for this router, it will remain in beta tough.

Tested with React 16.8.1.

How to install

Well, this is straightforward:

npm i hookrouter

How to use

A quick example:

import {useRoutes} from 'hookrouter';

const routes = {
    '/': () => <HomePage />,
    '/about': () => <AboutPage />,
    '/products': () => <ProductOverview />,
    '/products/:id': ({id}) => <ProductDetails id={id} />
};
	
const MyApp = () => {
    const routeResult = useRoutes(routes);
    
    return routeResult || <NotFoundPage />;
}

Routes are defined as an object. Keys are the routes, which are matched against the URL, the values need to be functions that are called when a route matches. You may define placeholders in your routes with :something which will be forwarded as props to your function calls so you can distribute them to your components.

The hook will return whatever the route function returned, so you may also return strings, arrays, React fragments, null - whatever you like.

Navigation

You can either navigate by importing the function navigate() from the package, or by importing the modified link component A.

Example with navigate()

import {useRoutes, navigate} from 'hookrouter';

const routes = {
    '/': () => <HomePage />,
    '/products/:id': ({id}) => <ProductDetails id={id} />
};
	
const handleClick = () => {
    navigate('/products/12');
};
	
const MyApp = () => {
    const routeResult = useRoutes(routes);
    
    return (
        <div>
            <Button onClick={handleClick}>Show my product</Button>
            {routeResult || <NotFoundPage />}			
        </div>		
    );
}

Example with link component

import {useRoutes, A} from 'hookrouter';

const routes = {
    '/': () => <HomePage />,
    '/products/:id': ({id}) => <ProductDetails id={id} />
};
	
const MyApp = () => {
    const routeResult = useRoutes(routes);
	
	return (
        <div>
            <A href="/products/12">Show my product</A>
            {routeResult || <NotFoundPage />}			
        </div>		
	);
}

The A component works internally with a default a HTML tag. It will forward all props to it, except an onClick function, which will be wrapped by the component, since it intercepts the click event, stops the default behavior and pushes the URL on the history stack, instead.

Nesting Routes

You may nest routes so the sub route calls continue to work with a sub part of the url.

Example

This is your main application:

import {useRoutes, A} from 'hookrouter';

const routes = {
    '/': () => <HomePage />,
    '/about*': () => <AboutArea />
};
	
const MyApp = () => {
    const routeResult = useRoutes(routes);
	
    return (
        <div>
            <A href="/about/people">Show about area</A>
            {routeResult || <NotFoundPage />}			
        </div>		
    );
}

The asterisk * at the end of the route indicates that the URL will continue but the later part is handled somewhere else. If the router notices an asterisk at the end, it will forward the remaining part of the URL to child routers.

See whats done now inside the <AboutArea /> component:

import {useRoutes, A} from 'hookrouter';

const routes = {
    '/people': () => 'We are happy people',
    '/company': () => 'Our company is nice'
};

const AboutArea = () => {
    const routeResult = useRoutes(routes);

    return (
        <div className="about">
            <A href="people">About people</A>
            <A href="company">About our company</A>
            {routeResult}
        </div>
    );
}

Using redirects

import {useRoutes, useRedirect} from 'hookrouter';

const routes = {
    '/greeting': () => 'Nice to meat you 🤤 ',
};

const MyApp = () => {
    useRedirect('/', '/greeting');
    const routeResult = useRoutes(routes);

    return routeResult || 'Not found';
}

Rule of thumb: apply the redirect right before you use the routing and everything is fine ;)

hookrouter's People

Contributors

gudleik 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.