Skip to content

victorteokw/react-use-path

Repository files navigation

react-use-path

NPM version Build Status Test Coverage License PR Welcome

The tiniest react URL path navigator.

Introduction

This package is designed for SPAs that manages the URLs and routes internally. The component based routers are bad in the React world. Do a console.log in a component wrapped under a <Route>, you will find the log is printed even it shouldn't be rendered. The reason we use map for list, use ternary operator for condition, is that we cannot wrap them into components. Natural javaScript control flows should be used. The correct way to do routing is with functions and switch.

react-use-path has a fairly simple API, which is just one line.

const [path, setPath] = usePath()

It can't be more simple yet powerful. It makes the coding style of an app looks more pure functional and consistent.

Installation

Install this package with npm.

npm i react-use-path -s

Usage

Get current path information.

const [path, setPath] = usePath()

const full = path.full // get the full path
const pathname = path.pathname // get the pathname component
const search = path.search // get the search component
const hash = path.hash // get the hash component

Navigate to new path.

const [path, setPath] = usePath()

setPath('/full-new-path') // alter entirely
setPath({ full: '/full-new-path' }) // save as above
setPath({ pathname: '/new-path' }) // alter pathname, keeps search and hash
setPath({ search: 'a=b' }) // alter search, keeps pathname and hash
setPath({ hash: null }) // remove hash, keeps pathname and search
setPath('/', { replace: true }) // do not update history state

License

MIT © Victor Teo

About

The tiniest react router implemented with hooks.

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published