Source

components/navigation/LoginLink.tsx

import React from 'react'

import {Link, LinkProps, useLocation} from 'react-router-dom'

type LoginLinkProps = LinkProps & {
    returnTo?: string
    label?: string

}

/**
 * `LoginLink` is a flavour of React Router `Link` that sends the
 * user to a login first before taking them to the destination
 * supplied in `returnTo`.
 *
 * If you don't supply `returnTo`, the user will be logged in and
 * return to the page the `LoginLink` is on (which is the default
 * behaviour of the normal login link).
 *
 * Use this when you want the user to go to another route in your
 * app but be logged in when they arrive there.
 *
 * @param [props.returnTo] the router URL that the user should be returned to after logging in
 * @param [props.label] the text to be used inside the Link
 *
 * @category Extras
 * @module LoginLink
 * @component
 */
export function LoginLink(props: LoginLinkProps) {

    let currentLocation = useLocation()

    // Set the return URL to current location or user provided location
    let postLoginPath = currentLocation.pathname
    if (props.returnTo) {
        postLoginPath = props.returnTo
    }

    // Set the link text to default or user provided label
    let linkText = 'Login here'
    if (props.label) {
        linkText = props.label
    }

    return <Link to={{pathname: '/login', state: { prevPath: postLoginPath }}} {...props}>{linkText}</Link>
}