Make ReactJS components from results of ChatGPT API

I’m trying to use ChatGPT APIs to make a chatbot on our website by React.

On, when users ask return a JavaScript code sample, the part of the code in the answer will be highlighted with a button Copy code.

enter image description here

We would like to realize similar thing on our website. By using the ChatGPT api, the assistant returns a string as follows:

Here's a simple JavaScript code sample: ``` // This function greets the user function greetUser(name) { console.log("Hello, " + name + "!"); } // Call the greetUser function greetUser("Alice"); ``` This code defines a function `greetUser` that takes a `name` argument and logs a greeting to the console. The function is then called with the argument `"Alice"`. When you run this code in a JavaScript environment, it should output `Hello, Alice!` to the console.

I then would like to know what’s the conventional approach to create JSX (with highlighted code block and Copy code button) from the above result.

One possible way is that, since the code part in an answer is often wrapped by markdown ```, we may try to look for it to identify the code. But there are two difficulties:

  • How can we make sure that the code part in an answer is wrapped by 3 backticks, I think this concerns writing a reliable prompt
  • If we want to rely on the 3 backticks, how can we easily and reliably identify the 3 backticks in a result string to make JSX component (with highlighted code block and Copy code button) from there? I’m wondering if there is any existing libraries to do so.

Could anyone help?