1.1.0 • Published 3 years ago

url-for-react v1.1.0

Weekly downloads
-
License
-
Repository
github
Last release
3 years ago

Introduction

url-for-react is a factory class to centralize router handling for page components.

A big problem using React's react-router-dom is the disconnect between Components, URL routes and parameters. This can end up in string constants all over the place ,making maintaining routes and components confusing.

The main idea is to have an exported factory Class that builds routes, links and parameter handling. This factory class is kept with the component, allowing easier handling of routing, parameter and component changes.

Importing the factory class into a component allows that component to route to or link using it. The component used by UrlFor does not need to be exported. This greatly simplifies handling routed components. Providing further decoupling.

Installation

npm install url-for-react

Quick start

Before

Routed component

    export default function Word(props) {
        const [word, setWord] = useState(null);
    
        useEffect(() => {
            setWord(props?.match?.params.word)
        }, [props]);
    
        return <h1>Word {word}</h1>
    }

Navigation and switching.

    <ul>
        <li>
            <Link to="/word/hello">Word hello</Link>
        </li>
    </ul>    
    <Switch>
        <Route exact path="/word/:word" component={Word}>
        </Route>
    </Switch>

After

Routed component

    export const routeWord = new UrlFor("/word/:word", Word, "Words", "Pick the word");

    export default function Word(props) {
        const [word, setWord] = useState(null);
    
        useEffect(() => {
            setWord(routeWord.matchId(props))
        }, [props]);
    
        return <h1>Word {word}</h1>
    }

Navigation and switching.

    <ul>
        <li>
            {routeWord.LinkTo('hello', 'hello')}
        </li>
    </ul>
    <Switch>
        {routeWord.Route()}
    </Switch>

Usage

Factory class

UrlFor(route, component, text, title)
parameterdescriptionexample
routea react-router-dom route specification"/show_word/:word"
componentthe React component that responds to the routeWord
texttext of a link if non supplied by LinkTo"Click me"
titlethe title= attribute for a LinkTo"Open the show word page"

methods

LinkTo

LinkTo(request_id, text, title)

Returns a react-router-dom Link component.

parameterdescription
request_idany single parameter for the link
texttext of the link
titlethe title= attribute

NOTE: only one parameter or none is allowed.

Route

Route()

Returns a react-router-dom Route component for use in <Switch>.

NOTE: always uses the exact attribute.

matchId

matchId(props)

Returns the parameter passed into the route. props can be props or match or params.

NOTE: only one parameter is supported.