The goal I am referring to is
Optional Bonus (you do not need to make this test pass): When I click a link rendered by my markdown previewer, the link is opened up in a new tab (HINT: read the Marked.js docs for this one!).
I have looked on the forum and one of the first responses to a similar question suggests to skip it since there is no relevant info in the DOCS in marked.js
Is this true? Should this optional bonus be skipped?
I tried implementing the code below but could not get it to execute properly. I found this code in a discussion in a GitHub thread about this issue.
const renderer = new marked.Renderer();
renderer.link = function( href, title, text ) {
return '<a target="_blank" href="'+ href +'" title="' + title + '">' + text + '</a>';
}
The code did work for me just make sure to put the argument with the object and renderer property
const renderer = new marked.Renderer();
renderer.link = (address = "#", title = "", content = "") => (
`<a target="_blank" href=${address} title=${title}>${content}</a>`
);
// then
marked(Your contend, { renderer }));
my code pen
1 Like
I read the docs but didn’t fully understand them. I got the tests to pass by adding the target="_blank" after the fact, using the following function as part of my ‘handleChange’ function:
const addTarget = () => {
const links = document.getElementById('preview').querySelectorAll('a');
links.forEach(l => l.setAttribute("target", "_blank"));
}
Wow, thanks I did not do the last line. If you dont mind, can you explain what the last line of your code is doing?
The line I am talking about is
marked(Your contend, { renderer }));
creative and simple. I like it!
1 Like
My bad, I am not good on the explaining part. on the last line I am parsing the markup string with the marked plugin
if you parse with pure javascript
document.getElementById('my element').innerHTML = marked('markup string', { renderer })
If its React it would be
const Your_render_ function = (props) {
return (
<div
dangerouslySetInnerHTML={marked("your markup string", { renderer })}>
</div>
)
}
In my case I used the html-react-parser instead of the dangerouslySetInnerHTML, in ordet to sanitize the markup.
Nice work, with few lines of code really simple, you got it to pass.
1 Like
I used react for this problem and at the end the only way I found to pass the test was to add {breaks:true} inside my dangerouslySetInnerHTML.
something like this:
<div className="preview" id="preview" dangerouslySetInnerHTML={{__html: marked(this.state.markdown, {breaks: true})}}>
</div>
unfortunately this not open the website in another Tab , but at least works for completing the test.
1 Like