When working with code in web applications is sometimes needed to have a responsive and easy-to-use interface for displaying and editing code. I had experience in the past creating a custom component for React but it was the first time trying it out with shadcn/ui
and there wasn’t anything either online about it.
So in this post I will introduce a new component CodeBlock
which will work with Tailwind CSS, React and shadcn/ui
together.
Key Features
- Language Support: The component can be configured to highlight syntax for different programming languages.
- Dark and Light Mode: It supports both dark and light themes.
- Customizable Styles: The component is wrapped in a
div
that can be styled using Tailwind CSS classes. - Accessibility and Ref Forwarding: By using
React.forwardRef
, the component can accept a ref that can be used for more direct manipulation or integration with other components that utilize refs.
Implementation
Here is the implementation of this components which you can add directly in the src/components/
folder.
The CodeBlock
component extends React.TextareaHTMLAttributes
, allowing it to inherit all textarea properties, which makes it more flexible. It also accept additional props such as language
and darkMode
to adjust its functionality.
Using Tailwind CSS, the outer div
of the component is styled to have a minimum height and responsive width, rounded borders, and padding.
CodeEditor Integration: The heart of the component is the CodeEditor
from @uiw/react-textarea-code-editor
, which is styled to fill the width of its container and match the outer div
’s background color based on the selected theme.
Example Usage
Here’s a simple example of how to use the CodeBlock
component in a React application:
An example project I did quickly using Vite can be found here: /blog/assets/codeblock-component-with-shadcn-ui-react-tailwind.zip