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

react-app-location

v1.2.1

Published

A package to avoid repetition with Routes, Links and URLs, and reduce boilerplate with location param parsing in React Apps

Downloads

841

Readme

react-app-location

Declarative locations for React apps. Avoids repetition with Routes and Links, and reduces boilerplate with parsing and casting parameters from URLs.

This package depends on React Router 4. If you are not using React Router 4, take a look at app-location, which is router-agnostic.

Install

npm install react-app-location --save

Usage

A Location is an endpoint that your app supports. It specifies a path, and can optionally specify path and query string parameters.

A Location keeps your code DRY as the Location is defined in one place and used throughout your code to generate Routes, Links and URLs.

When generating a Link or URL, you can provide a literal object of values, and the values will be mapped to path and query string parameters and inserted into the resulting URL.

Path and query string parameters are specified as Yup schemas. A Route that is generated from a Location automatically parses the URL and extracts the path and query string parameters. These are validated according to the schema, cast to the appropriate data types, and passed as props to your component. If a required parameter is missing or a parameter fails validation, the Route will render the specified <Invalid /> component. This eliminates a boatload of boilerplate.

import React from "react";
import { Link, BrowserRouter, Switch, Route } from 'react-router-dom';
import * as Yup from 'yup';
import Location from "react-app-location";

const HomeLocation = new Location('/');
const ArticleLocation = new Location('/articles/:id', { id: Yup.number().integer().positive().required() });

const App = () => (
    <BrowserRouter>
        <Switch>
            {/* Regular Route */}
            <Route path={HomeLocation.path} component={Home} exact />
            {/* Route with params automatically passed as props to your component */}
            {ArticleLocation.toRoute({ component: Article, invalid: NotFound }, true)}
            <Route component={NotFound} />
        </Switch>
    </BrowserRouter>
);

const Home = () => (
    <div>
        <header>Articles</header>
        <ul>
            {/* <Link to={'/articles/1'}>Article 1</Link> */}
            <li>{ArticleLocation.toLink('Article 1', {id: 1})}</li>
            {/* <Link to={'/articles/2'}>Article 2</Link> */} 
            <li>{ArticleLocation.toLink('Article 2', {id: 2})}</li> 
            {/* Also works */}
            <li><Link to={ArticleLocation.toUrl({id: 3})}>Article 3</Link></li>  
            {/* Clicking results in <NotFound /> */}
            <li><Link to={ArticleLocation.toUrl({id: 'oops-not-an-int'})}>Article 4</Link></li>  
            {/* Also results in <NotFound /> */}
            <li><Link to={'/articles/oops-not-an-int'}>Article 5</Link></li>  
        </ul>
    </div>
);

//id has been parsed from the URL, cast to int, and merged into props
const Article = ({id}) => <header>`Article ${id}`</header>;

const NotFound = () => (
    <div>
        <header>Page not found</header>
        <p>Looks like you have followed a broken link or entered a URL that does not exist on this site.</p>
    </div>
);

API

Location.ctor(path: string, pathParamDefs: ?schema, queryStringParamDefs: ?schema): Location

Defines a Location. pathParamDefs and queryStringParamDefs are optional and specified as Yup schemas.

Location.toUrl(params: ?object): string

Builds a URL with param values plugged in.

Location.toLink(children: func || node, params: ?object, props: ?object): element

Generates a React Router 4 Link passing the generated URL as the to prop.

Generates a React Router 4 Route which parses params and passes them as props to your component.

Location.path: string

Returns the path property which you can use when building a Route by hand, e.g., without params passed as props.

Location.parseLocationParams(location: object = window.location, ?match: object) : object

Returns a literal object containing the parameters parsed from the React Router 4 location (or window.location) and match (optional) props. Each parameter is validated and cast to the data type indicated in the schema. If validation fails, returns null.

You can manually call parseLocationParams from within your component to get the location parameters if you prefer to not use the automatic param parsing and prop injection provided by Location.toRoute.

Location.isValidParams(params: ?object): boolean

Returns a boolean indicating if the parameters are valid.

Try it out

Online

Demo

Local

  1. git clone https://github.com/bradstiff/react-app-location.git
  2. cd react-app-location
  3. npm install
  4. npm start
  5. Browse to http://localhost:3001

Contribute

You're welcome to contribute to react-app-location.

To set up the project:

  1. Fork and clone the repository
  2. npm install

The project supports three workflows, described below.

Developing, testing and locally demoing the component

Source and tests are located in the /src and /test folders.

To test: npm run test.

To run the demo, npm start. The demo can be seen at http://localhost:3001 in watch mode.

Publishing the module to npm

npm publish

This will use babel to transpile the component source, and publish the component and readme to npm.

Publishing the demo to github-pages

npm run publish-demo

This will build a production version of the demo and publish it to your github-pages site, in the react-app-location directory.

Note that webpack.config is set up to handle the fact the demo lives in a directory.

Also note that github-pages does not support routers that use HTML5 pushState history API. There are special scripts added to index.html and 404.html to redirect server requests for nested routes to the home page.