Skip to content
Snippets Groups Projects
Link.tsx 1.76 KiB
Newer Older
// From https://www.gatsbyjs.com/docs/reference/built-in-components/gatsby-link/

import React from "react"
Julien MARGAIL's avatar
Julien MARGAIL committed
import { graphql, useStaticQuery, Link as GatsbyLink } from "gatsby"
interface Props {
Toavina's avatar
Toavina committed
    children?: React.ReactNode
    to: string
    activeClassName?: string
    partiallyActive?: any
Julien MARGAIL's avatar
Julien MARGAIL committed
    onClick?: any
    className?: any
}

// Since DOM elements <a> cannot receive activeClassName
// and partiallyActive, destructure the prop here and
// pass it only to GatsbyLink
const Link = ({
Toavina's avatar
Toavina committed
    children,
    to,
    activeClassName,
    partiallyActive,
    onClick,
    className,
Toavina's avatar
Toavina committed
    ...other
Julien MARGAIL's avatar
Julien MARGAIL committed
    // Basé sur les données de l'API GraphQL = liste des pages
    const data = useStaticQuery(graphql`
        query appPages {
            allSitePage {
                nodes {
                    path
                }
            }
        }
    `)
Julien MARGAIL's avatar
Julien MARGAIL committed
    // /^https?:\/\//
    // Si "to" n'est pas dans la liste des pages, c'est un lien externe
    // ignore le "/" à la fin du 'path' et de 'to'
    const internal = data.allSitePage.nodes.find(
        ({ path }) => path.replace(/\/+$/, "") === to.replace(/\/+$/, "")
    )
Toavina's avatar
Toavina committed
    // Use Gatsby Link for internal links, and <a> for others
    if (internal) {
Julien MARGAIL's avatar
Julien MARGAIL committed
        // console.log("Internal", to)
Toavina's avatar
Toavina committed
        return (
            <GatsbyLink
                to={to}
                activeClassName={activeClassName}
                partiallyActive={partiallyActive}
                onClick={onClick}
Julien MARGAIL's avatar
Julien MARGAIL committed
                className={className}
Toavina's avatar
Toavina committed
                {...other}
            >
                {children}
            </GatsbyLink>
        )
    }
Julien MARGAIL's avatar
Julien MARGAIL committed

    // console.log("External", to)
Julien MARGAIL's avatar
Julien MARGAIL committed
        <a href={to} {...other} onClick={onClick} className={className}>
Toavina's avatar
Toavina committed
            {children}
        </a>
    )
}
Toavina's avatar
Toavina committed
export default Link