5

I have a gatsby app in which I am rendering rich text content. everything is working well, other than me being unable to fetch the text which I hyperlinked in the contentful CMS. Current code looks like below and I can get the url or uri (in contentfuls case), but not the value/text which I hyperlinked. Can anyone help?

import React from 'react';
import { graphql, Link } from 'gatsby';
import Img from 'gatsby-image';
import { renderRichText } from 'gatsby-source-contentful/rich-text';

import { BLOCKS, MARKS, INLINES } from '@contentful/rich-text-types';

const Bold = ({ children }) => <span className="bold">{children}</span>;
const Text = ({ children }) => <p className="align-center">{children}</p>;

const website_url = 'https://stackoverflow.com';

// Setting the rendering options. Same as:
// https://github.com/contentful/rich-text/tree/master/packages/rich-text-react-renderer
const options = {
    renderMark: {
        [MARKS.BOLD]: (text) => <Bold>{text}</Bold>
    },
    renderNode: {
        [INLINES.HYPERLINK]: ({ data }) => (
            <a
                href={data.uri}
                target={`${data.uri.startsWith(website_url) ? '_self' : '_blank'}`}
                rel={`${data.uri.startsWith(website_url) ? '' : 'noopener noreferrer'}`}
            >
                {/* {node.content[0].value} */}
                {console.log(data)}
            </a>
        ),
        [BLOCKS.PARAGRAPH]: (node, children) => <Text>{children}</Text>,
        [BLOCKS.EMBEDDED_ASSET]: (node) => <Img fluid={node.data.target.fluid} />
    }
};
function privacy({ data }) {
    // console.log(data);

    const description = data.allContentfulBlogPost.nodes[0].bodyRichText;
    return <div>{description && renderRichText(description, options)}</div>;
}

export default privacy;
export const pageQuery = graphql`
    query MyQuery {
        allContentfulBlogPost {
            nodes {
                bodyRichText {
                    raw
                    references {
                        ... on ContentfulAsset {
                            contentful_id
                            __typename
                            fluid {
                                ...GatsbyContentfulFluid
                            }
                        }
                    }
                }
            }
        }
    }
`;
Ferran Buireu
  • 28,630
  • 6
  • 39
  • 67
Jegs
  • 579
  • 1
  • 6
  • 14

1 Answers1

15

Contentful DevRel here.

I think what you're looking for is children. It's similar to how you're rendering the paragraph.

[INLINES.HYPERLINK]: ({ data }, children) => (
  <a
    href={data.uri}
    target={`${data.uri.startsWith(website_url) ? '_self' : '_blank'}`}
    rel={`${data.uri.startsWith(website_url) ? '' : 'noopener noreferrer'}`}
  >{children}</a>
)
General Grievance
  • 4,555
  • 31
  • 31
  • 45
stefan judis
  • 3,416
  • 14
  • 22