Search code examples
javascriptreactjslinkify

React: Detect and wrap links in custom element


Any help on this would be appreciated. I have blocks of text with links and have been using linkifyjs's React component to automatically wrap the links with anchor tags. However, now I would like to display a button next to each link with some custom behavior. Is there a way to wrap links in a custom component, say something like this?

function CustomLink(props) {
  return (
    <>
      <a href={props.link}>{props.text}</>
      <button>Click me</button>
    </>
  )
}

I know that I can pass in something like tagName: 'strong' in the options object, but it won't allow me to pass a custom React element. I get an error message if I try to do something like this (which works for built-in tags, like 'strong'):

// error => Element type is invalid: expected a string (for built-in components) or a
// class/function (for composite components) but got: object.

function CustomLink(link) {
  console.log(link)
  return (
    <a href={link}>{link}</a>
  )
}

function TextWithLinks(props) {
  return (
    <Linkify className="d-inline" options={{tagName: CustomLink}}>
      {props.text}
    </Linkify>
  )
}

Thanks for any help!


Solution

  • use the format option and pass it a function.

    function CustomLink({link}) {
        return (
            <>
                <a href={link}>{link}</a>
                <button>Click Me</button>
            </>
        )
    }
    
    function TextWithLinks(props) {
    
        function formatter(value, type) {
            return <CustomLink link={value}/>
        }
    
        return (
            <Linkify className="d-inline" options={{tagName: 'div', format: formatter }}>
                {props.text}
            </Linkify>
        )
    }