damunga
damunga

Reputation: 115

How to parse Embeddable Links from Markdown and render custom React Components

I want to embed Twitter tags from Markdown to Html. I am currently using react-markdown to render like below


import gfm from 'remark-gfm'

const content = `#Hello <br/><hr/> <p>Please check out this tweet</p><br/> <p>https://twitter.com/adamwathan/status/1378480731651981322</p>`

....

<Markdown
 plugins={[gfm]}
 children={content} / >

I hoped to be able to parse anything that starts with https://twitter.com so i could render a React Component for the same.

Upvotes: 3

Views: 10598

Answers (1)

juliomalves
juliomalves

Reputation: 50368

You could pass a custom a component to ReactMarkdown that would handle links with your own logic.

import Markdown from 'react-markdown'
import remarkGfm from 'remark-gfm'

const content = `
  # Hello
  Please check out this tweet: https://twitter.com/adamwathan/status/1378480731651981322
`

export default Index() {
    return (
        <Markdown
            remarkPlugins={[remarkGfm]}
            components={{
                a: props => {
                    return props.href.startsWith('https://twitter.com') ? (
                        <CustomTwitterComponent url={props.href} /> // Render Twitter links with custom component
                    ) : (
                        <a href={props.href}>{props.children}</a> // All other links
                    )
                }
            }}
        >
            {content}
        </Markdown>
    )
}

Upvotes: 8

Related Questions