Custom links with serializeHyperlink do not render

I'm passing a custom link to serializeHyperlink in a component (per the Gatsby documentation) in order to open external links in a new tab, but nothing is rendered.

The component is a slice.

I can pass a target="_blank" with the htmlSerializer, but want the control over the links that serializeHyperlink is supposed to provide.

customLink.js:

import React from 'react'
import { Link } from 'gatsby'

import { linkResolver } from './linkResolver'

export const CustomLink = (type, element, content, children) => {
    
    if (element.data.link_type === 'Document') {
        <Link to={linkResolver(element.data)} key={element.data.id}>
            {content}
        </Link>
    }
    if (element.data.link_type === 'Media') {
        <a href={element.data.url} target="_blank" rel="noopener noreferrer">
            <strong>{content}</strong>
        </a>
    }
    if (element.data.link_type === 'Web') {
        <a href={element.data.url} target="_blank" rel="noopener noreferrer">
            {content}
        </a>
    }
    return null
}

Hello @jgunderson

Welcome to the Community Forum.

The code looks good for me except for one thing that after each if statement, the rendered HTML should be in return statement like in your code:

import React from 'react'
import { Link } from 'gatsby'

import { linkResolver } from './linkResolver'

export const CustomLink = (type, element, content, children) => {
    
    if (element.data.link_type === 'Document') {
       return `<Link to={linkResolver(element.data)} key={element.data.id}>
            {content}
        </Link>`
    }
    if (element.data.link_type === 'Media') {
        return `<a href={element.data.url} target="_blank" rel="noopener noreferrer">
            <strong>{content}</strong>
        </a>`
    }
    if (element.data.link_type === 'Web') {
        return `<a href={element.data.url} target="_blank" rel="noopener noreferrer">
            {content}
        </a>`
    }
    return null;
}

Else it will always return null. Can you please apply the return statement?

Let me know If you have any doubt.

Thanks,
Priyanka

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.