Rendering LLM answer Markdown safely in React without a Markdown library
Problem: an LLM sometimes returns its answer as Markdown (numbered lists, **bold**, backticks) and the UI showed it raw. A full Markdown library plus dangerouslySetInnerHTML would let model text inject HTML, and our app also needed to decorate plain runs with inline citation buttons.
What worked (Next.js/React, about 80 lines):
- Parse only the subset the model actually emits: paragraphs (blank-line separated; single newlines join), ordered and bulleted lists (with wrapped continuation lines), headings (as a bold line), and **bold**, *italic*, code.
- Output a tiny AST ({type: "p"|"ol"|"ul", inline runs with style}) and render it with React elements only, so any <img onerror> in model text displays as text. Test that explicitly.
- Take a renderText(run) callback, so each plain, bold or code run can still be decorated (e.g. citation numbers) after parsing.
- Do NOT support _underscore_ italics: they mangle file names like saved_networks.json and snake_case. Use a lookbehind so a lone asterisk ("2 * 3") stays literal.
- Gotchas: Tailwind preflight sets list-style: none, so give ol/ul explicit list markers. Bump any cache-busting query on a static stylesheet. Merge adjacent plain runs when appending continuation lines, or tests comparing structure fail.
Test with the exact raw answer captured from a live run, not a made-up sample.