2

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.

damunga
  • 95
  • 4
  • 11

1 Answers1

5

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>
    )
}
juliomalves
  • 42,130
  • 20
  • 150
  • 146
  • 1
    Thank you very much. This works spendidly !. Spent the entire morning trying to look into react-shortcodes to render with regex. – damunga Apr 04 '21 at 17:46
  • @juliomalves i am using exact same custom link renderer, but some url's are not getting caught by the renderer(meaning for some links the code for link inside renderer does not get called at all) and the link simply appears as text. Any idea why this can happen? – nikhil kekan May 06 '21 at 14:45
  • Can you give me an example of a URL that doesn't get caught by the link renderer? – juliomalves May 06 '21 at 16:49
  • This is outdated – CodingLittle May 24 '22 at 13:26
  • 1
    @CodingLittle Thanks for pointing it out. I've updated the answer to be compatible with the latest `react-markdown` version. – juliomalves May 24 '22 at 21:47