Unlock the Power of Code Snippets with Multi-Language Support
Are you tired of cluttered code blocks in your blog or developer documentation project? Do you want to provide a seamless user experience with language preferences that persist across multiple pages? Look no further! In this tutorial, we’ll show you how to build a code snippet block with multi-language support using React and Recoil.
Getting Started
Before we dive in, make sure you have a fundamental understanding of React and Node installed (version 8 or higher). You can clone our starter repo to follow along.
Building the Code Snippet Component
Our code snippet component can be reused across the entire site, making it perfect for custom developer documentation or technical blogs. To aid readability, we’ll split the logic into two components: CodeSnippet
and CodeGroup
.
CodeSnippet
: Displays the code and handles code syntax highlightsCodeGroup
: Wraps theCodeSnippet
component while adding multi-language support
Adding Multi-Language Support with CodeGroup
The CodeGroup
component accepts a code prop of type object, which stores the code to be displayed for each language. We’ll store these objects in a utils/{page_name}Requests.js
file and import them when needed.
Saving Language Preference with Recoil
Recoil is a lightweight React state management library that allows us to persist language across multiple pages or even remember a user’s preferred language when they return to your website. We’ll use Recoil to save the user’s language preference.
Setting Up Recoil
First, add Recoil to your project by running yarn add Recoil
. Then, import RecoilRoot
from Recoil and wrap the App
component with RecoilRoot
.
Creating the CodeLanguageState Atom
We’ll create an atom to store the code language state. The atom function accepts a JavaScript object with a unique identifier, default state, and more.
Updating CodeGroup with Recoil
We’ll update the CodeGroup
component to use Recoil’s useRecoilState
Hook to read and write to the codeLanguageState
atom.
Session Persistence with Recoil
Using Recoil and recoil-persist
, we can add session persistence to our app in three easy steps. This way, the language preference will persist even after a page refresh.
Try it Out!
Check out our live demo to see the code snippet block in action. You can also clone our Github repo to play around with the final code.
Take Your App to the Next Level with LogRocket
LogRocket is a powerful tool that helps you create better digital experiences. With LogRocket, you can track errors, performance issues, and user behavior in real-time. Sign up for a free trial today!