Custom newline/hard-break rule with React parser
Hi there! I'm having some issues creating a custom rule that will allow all newlines to be treated as a hard-break, here's an example of the behaviour I'm looking for:
Line 1\nLine 2\n\nLine 4\n\n\n\nLine 8\nLine 9\n\nLine 11
should return:
| Content | Raw |
|---|---|
Line 1 |
Line 1<br /> |
Line 2 |
Line 2<br /> |
<br /> |
|
Line 4 |
Line 4<br /> |
<br /> |
|
<br /> |
|
<br /> |
|
Line 8 |
Line 8<br /> |
Line 9 |
Line 9<br /> |
<br /> |
|
Line 11 |
Line 11 |
EDIT: The table above says that all newlines should be replaced with <br /> but this doesn't have to be the case, I'm just looking for a way to translate all newlines created by the user into the content like this - my attempts keep wrapping each text node in a div and therefore none of the newlines are being rendered (see here)
I understand this isn't exactly how the specifications describe how newlines should work but that's the whole reason I've wanted to add a custom rule to allow for more than one break without doing weird stuff.
I've been trying to solve this for quite some time and I've had a look at similar issues such as #61 (and in other implementations) but even after adopting the code from that issue, I've had trouble getting it to work the way I want: multiple newlines in a row only count as one. Any help would be appreciated, thank you!
I know this issue is old, this is for anyone who is looking for similar solution.
I've also tried to do the same, but it's not working. The workaround I did is to add support to turn \ + ENTER to become a line break.
Some markdown parser supports to add multiple \ which will be converted to <br>. We can do the same here with a simple new rule.
// Extention inspired from https://github.com/Khan/simple-markdown/issues/61#issuecomment-461566933
const newlineRule = {
order: defaultRules.newline.order - 0.5,
match: (source) => {
// This will match "\" plus a line break
return /^\\\n/.exec(source);
},
parse: (capture) => {
return {
content: capture[1],
};
},
html: () => "<br>",
};