I am working on a next.js blog project. To render the blog text on a page, I am using graphql to externally fetch markdown and then render it on to the next.js app. In order to do so I am currently using the marked-react package which works somewhat well. The markdown gets rendered on the page but some of the styling seems to be wonky.
As an overall high level question, what kind of strategies can I implement to retrieve the markdown and then once loaded be able to tease through it and add the necessary class, id stylings? I suspect what I'm doing right now is not the correct approach.
This is what I'm doing essentially to make a page work.
const Post = ({ postData }) => {
useEffect(() => {
let title = document.querySelector('h1');
title.classList.add(styles.title);
let pTags = document.querySelectorAll('p');
pTags.forEach(element => {
element.classList.add(styles.pad);
});
let pre = document.querySelectorAll('pre');
pre.forEach(element => {
element.classList.add(styles.code);
});
}, []);
return (
<Flex direction={'column'}>
<div className={styles.container}>
<Markdown>{postData.content}</Markdown>
</div>
</Flex>
);
};
......code.....
export default Post;
Essentially, what I'm currently doing is fetching my data and then I use a useEffect to apply scss stylings once everything is loaded on to the dom. As a general blanket approach this works somewhat good but when I need to apply more directed stylings, I'm at a loss. What other approaches can I use to achieve what I need to do if any?
Using this approach will lead to access to some DOM nodes outside the markdown, for example :
let pTags = document.querySelectorAll('p');
pTags.forEach(element => { element.classList.add(styles.pad); });
This can select all p elements even those outside the markdown, and that will lead to affecting the style of those elements. You can use CSS to style your markdown:
.container h1 {
//put the style of class title
}
.container p {
//put the style of class pad
}
.container pres{
//put the style of class code
}