Last active
January 3, 2024 20:43
-
-
Save AndrewJHart/ef3753643f045cd2e7ca36457dfacf80 to your computer and use it in GitHub Desktop.
react-markdown w/ rehype-external-links for opening markdown links in a new tab
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Uses react-markdown w/ rehype-external-links to demo how to parse markdown | |
* so that the links open in a new tab as external links in your react application. | |
* React-markdown use to have a property that would allow you | |
* to require all links be opened in a new tab but they deprecated it and moved | |
* to a more pluggable architecture using rehype and remark. The plugin required | |
* for react-markdown is rehype-external-links but the documentation doesn't | |
* explain how to use it with react-markdown. Thus here is an example: | |
* | |
* you can find it here https://www.npmjs.com/package/react-markdown - | |
* @note - the original example I found was buried in a github issue and can be found below: | |
* https://github.com/remarkjs/react-markdown/pull/762#issuecomment-1806576871 | |
* | |
*/ | |
import React from 'react'; | |
import rehypeExternalLinks from 'rehype-external-links' | |
const MarkdownFeed = ({ props }) => { | |
// set it up so only a few of the markdown attributes are allowed | |
const allowedElements = ['a', 'link', 'text', 'p', 'bold', 'strong']; | |
return ( | |
<ReactMarkdown | |
allowedElements={allowedElements} | |
rehypePlugins={[[rehypeExternalLinks, { target: '_blank' }]]} | |
> | |
{children} | |
</ReactMarkdown> | |
); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment