remarkjs / react-markdown

Markdown component for React
https://remarkjs.github.io/react-markdown/
MIT License
13.3k stars 877 forks source link

`<br>` in table #392

Closed ponsfrilus closed 4 years ago

ponsfrilus commented 4 years ago

I've read the similar issues (c.f. #6, #33, #230 and #233) and I think my question add another case for which one may want to use <br>: tables.

My use case is that I source a README from GtiHub and render it with react-markdown in my website. The README get some <br> in table cell, and some list (<ul><li></li></ul>).

I've tried the remark-breaks plugin, but this is not its purpose.

This markdown-it issue gives good example on br and list in a markdown table. I've also found this common mark talk on the topic.

Examples from here:

Is there, by any chance, a plugin which already handle that ?

ChristianMurphy commented 4 years ago

I'm not sure what the question/issue is? Both of the examples you posted work. As you noted, there isn't an official CommonMark syntax for breaks in tables yet, and by extension there isn't one here. If you have a specifc syntax in mind, it can be created through a remark plugin. You can find more information on creating plugins here: https://unifiedjs.com/learn/

KosukeZaizen commented 3 years ago

I don't know if this is the best way, but the code below is working for me.

import React, { ReactChildren } from "react";
import ReactMarkdown from "react-markdown";
import gfm from "remark-gfm";

~~~~~~~~~~~~~

        <ReactMarkdown
            source={source}
            renderers={{
                tableCell: TableCellRender,
            }}
            plugins={[gfm]}
        />

~~~~~~~~~~~~~

function TableCellRender({
    children,
    isHeader,
    align,
    ...rest
}: {
    children: JSX.Element | JSX.Element[];
    isHeader: boolean;
    align: "left" | "right" | "center";
    [key: string]: any;
}) {
    const content = Children.map(children, c => {
        if (c.props.value === "<br />") {
            return <br />;
        }
        return c;
    });

    if (isHeader) {
        return (
            <th {...rest}>
                {content}
            </th>
        );
    }
    return (
        <td style={{ textAlign: align }} {...rest}>
            {content}
        </td>
    );
}

Version:

        "react": "^17.0.1",
        "react-dom": "^17.0.1",
        "react-markdown": "^5.0.3",
        "remark-gfm": "^1.0.0"
kangfenmao commented 1 month ago
image