skip to Main Content

I am using React ReactMarkdown to display a string which have numbered lists in it , the string is fetched using an api. But the it succesfully arranges the string line by line according to lists but it fails to display the numbers.

import React, { useEffect, useRef } from "react";
import ReactMarkdown from "react-markdown";
import remarkGfm from "remark-gfm";

const Chat = ({ messages }) => {

  const messageContainerRef = useRef(null);
  useEffect(() => {
    if (messageContainerRef.current) {
      messageContainerRef.current.scrollTop =
        messageContainerRef.current.scrollHeight;
    }
  }),
    [messages];
  return (
    <div
      className="w-full md:w-[50%] text-start overflow-y-scroll max-h-full"
      ref={messageContainerRef}
    >
      <div className="flex flex-col gap-8 items-start">
        {messages.length > 0 ? (
          messages.map((message, index) => (
            <div
              className="text-white flex gap-3 items-start justify-center"
              key={index}
            >
              {message.role == "user" ? (
                <div className="w-7 h-7 rounded-2xl text-white text-center bg-[#3e3e54] border border-gray-50">
                  U
                </div>
              ) : (
                <img
                  src="/img/doge.webp"
                  alt=""
                  className="w-7 h-7 rounded-2xl"
                />
              )}
              <div>
                <h1 className="font-bold ">
                  {message.role == "user" ? "You" : "VoiceGPT"}
                </h1>
                {message.role == "user" ? (
                  <p>{message.content}</p>
                ) : (
                  <ReactMarkdown remarkPlugins={[remarkGfm]}>
                    {message.content}
                  </ReactMarkdown>
                )}
              </div>
            </div>
          ))
        ) : (
          <>
            <button></button>
          </>
        )}
      </div>
    </div>
  );
};

export default Chat;

Result i got

Develop a plan

Make a list of tasks

Prioritize tasks

Start working on the first task

Complete the task

Evaluate progress

Adjust plan if necessary

Move on to the next task

Repeat steps 5-8 until all tasks are completed

Celebrate your accomplishments!

expected result

  1. Develop a plan
  2. Make a list of tasks
  3. Prioritize tasks
  4. Start working on the first task
  5. Complete the task
  6. Evaluate progress
  7. Adjust plan if necessary
  8. Move on to the next task
  9. Repeat steps 5-8 until all tasks are completed
  10. Celebrate your accomplishments!

I tried installing and using remarkGfm , but that doesnt seems to work.

2

Answers


  1. please try this: you have to generate the numbers by yourself try this code :

    import ReactMarkdown from "react-markdown";
    import gfm from "remark-gfm";
    
    const YourComponent = ({ message }) => {
    const addNumbersToMarkdownList = (markdown) => {
    let lineNumber = 1;
    
    // Split the markdown content by lines
    const lines = markdown.split("n");
    
    // Process each line
    const numberedMarkdown = lines.map((line) => {
      if (line.trim().startsWith("-")) {
        // If the line starts with '-', add the auto-generated number as a prefix
        return `${lineNumber++}. ${line.trim().substring(1)}`;
      }
      return line;
      });
    
     // Join the lines back together
      return numberedMarkdown.join("n");
     };
    
     const numberedContent = addNumbersToMarkdownList(message.content);
    
     return <ReactMarkdown remarkPlugins={[gfm]} children={numberedContent} 
     />;
     };
     export default YourComponent;
    
    Login or Signup to reply.
  2. I need to see your sample value (message.content) that want to displayed. Here I found sandbox that might help you.

    https://codesandbox.io/p/sandbox/react-markdown-forked-tvwdkp?file=%2Fsrc%2FApp.tsx

    Here is the code of above sandbox:

    import { useState } from "react";
    import "./styles.css";
    
    import ReactMarkdown from "react-markdown";
    import gfm from "remark-gfm";
    
    const startingText = `# Hello
    
    1. banana
    2. apple
    3. orange
    
    https://example.org
    
    ```sh
    # Code block 
    ```
    
    ![Placeholder image](https://unsplash.it/600/400)
    
    ~~strike~~ this
    
    ## TODO
    
    * [ ]  This
    * [ ]  That
    * [x]  The other
    
    |Fahrenheit|Celsius|Kelvin|
    |---:|---:|---:|
    |-459.67|-273.15|0|
    |-40|-40|233.15|
    |32|0|273.15|
    |212|100|373.15|
    `;
    
    export default function App() {
      const [text, setText] = useState<string>(startingText);
      return (
        <div style={{ width: "100%", maxWidth: 600, margin: "0 auto" }}>
          <textarea
            style={{ width: "100%" }}
            rows={10}
            value={text}
            onChange={(e) => setText(e.target.value)}
          />
          <ReactMarkdown plugins={[gfm]} children={text} />
        </div>
      );
    }
    

    package.json

    {
      "name": "react-markdown",
      "version": "1.0.0",
      "description": "",
      "keywords": [],
      "main": "src/index.tsx",
      "dependencies": {
        "@types/react-syntax-highlighter": "13.5.0",
        "react": "17.0.1",
        "react-dom": "17.0.1",
        "react-markdown": "5.0.3",
        "react-scripts": "4.0.0",
        "react-syntax-highlighter": "14.0.0",
        "remark-gfm": "1.0.0"
      },
      "devDependencies": {
        "@types/react": "17.0.0",
        "@types/react-dom": "17.0.0",
        "typescript": "4.1.3"
      },
      "scripts": {
        "start": "react-scripts start",
        "build": "react-scripts build",
        "test": "react-scripts test --env=jsdom",
        "eject": "react-scripts eject"
      },
      "browserslist": [
        ">0.2%",
        "not dead",
        "not ie <= 11",
        "not op_mini all"
      ]
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search