react-code-block icon indicating copy to clipboard operation
react-code-block copied to clipboard

Any tips for making this more responsive?

Open ConorCorp opened this issue 11 months ago • 2 comments

https://github.com/user-attachments/assets/788f056a-3cc5-45ac-b1e6-e91c16c16b68

Would love to see the code block act more responsively for mobile. Potentially overflowing with scroll like on resend.com. Will probably implement it myself later but let me knew if you've a quick tip.

Thanks for the library!

ConorCorp avatar Jan 29 '25 12:01 ConorCorp

I was able to fix this for now, but its a bit janky.

My solution

  1. Use a grid instead of a table-row/table-cell: grid-cols-[min-content_auto].
  2. Add w-20 md:w-full to <CodeBlock.LineContent className="w-20 md:w-full">
  3. Add overflow-x-auto to <CodeBlock.Code className="bg-gray-900 !p-6 rounded-xl shadow-lg min-h-[400px] overflow-x-auto">

It's not the best solution as its arbitrarily sizes the 2nd grid content column to w-20 so it doesn't mess with the parent's width.

Let me know if you have a better solution!

    <CodeBlock tokens={tokens}>
      <div className="relative w-full">
        <CodeBlock.Code className="bg-gray-900 !p-6 rounded-xl shadow-lg min-h-[400px] overflow-x-auto">
          <div className="grid grid-cols-[min-content_auto]">
            <CodeBlock.LineNumber className="pr-4 text-sm text-gray-500 text-right select-none" />
            <CodeBlock.LineContent className="w-20 md:w-full">
              <CodeBlock.Token />
            </CodeBlock.LineContent>
          </div>
        </CodeBlock.Code>
        <Button
          className="absolute top-2 right-2 rounded-full"
          variant="outline"
          size="sm"
          onClick={copyCode}
        >
          {state.value ? "Copied!" : "Copy code"}
        </Button>
      </div>
    </CodeBlock>

ConorCorp avatar Jan 29 '25 18:01 ConorCorp

I'll maybe add a better example for this in the docs, but for the meantime you can refer to the styles applied in the code blocks on https://react-code-block.netlify.app/usage page.

Image

blenderskool avatar Jan 29 '25 18:01 blenderskool