Skip to content

Component for Link #34

@chrisflatley

Description

@chrisflatley

In material-ui link the component prop allows for composition which is necessary for say react-router-dom.

https://material-ui.com/guides/composition/#link

This gets lost through here.

I'd added it back by declaring it:

import React from 'react'
import {
  Link as RouterLink,
  LinkProps as RouterLinkProps
} from 'react-router-dom'
import { Link as ComponentsLink } from '@committed/components'

/**
 * The underlying Material UI allows the component used to render the Link to be changed.
 * This is function is not publicised by @committed/components Link.
 * We add that property (component) back and then declare our new Link takes the
 * options from RouterLink too (which is does, these are passed to the component).
 */
const LinkWithComponent = ComponentsLink as React.FC<
  RouterLinkProps & {
    component: React.ElementType
  }
>

interface Props extends RouterLinkProps {
  children: React.ReactNode
}

export const Link: React.FC<Props> = props => {
  // If an external link?
  if (typeof props.to === 'string' && props.to.startsWith('http')) {
    return (
      <ComponentsLink href={props.to} target="_blank">
        {props.children}
      </ComponentsLink>
    )
  }

  // Else use a internal link, rendered using RouterLink
  return (
    <LinkWithComponent component={RouterLink} {...props}>
      {props.children}
    </LinkWithComponent>
  )
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions