shopify-rich-text-renderer
shopify-rich-text-renderer copied to clipboard
Add an option to add classes directly to HTML elements
In this PR, I add a way for developers to apply a string of classes directly to each HTML element. This would be especially useful for developers using an atomic css framework like Tailwind CSS. This change also allows developers to create a wrapper class or component that makes re-using the default classes very easy.
Example of the new options. Developers can pick and choose which elements they want to apply classes to, but below a list all of the possible elements we can apply classes to.
const options = {
scoped: false,
classes: {
p: 'mt-3 text-lg', // paragraph classes
h1: 'mb-4 text-2xl md:text-4xl', // heading1 classes
h2: 'mb-4 text-xl md:text-3xl', // heading2 classes
h3: 'mb-3 text-lg md:text-2xl', // heading3 classes
h4: 'mb-3 text-base md:text-lg', // heading4 classes
h5: 'mb-2.5 text-sm md:text-base', // heading5 classes
h6: 'mb-2 text-xs md:text-sm', // heading6 classes
ol: 'my-3 ml-3 flex flex-col gap-y-2', // order list classes
ul: 'my-3 ml-3 flex flex-col gap-y-2', // unordered list classes
li: 'text-sm md:text-base', // list item classes
a: 'underline text-blue-500 hover:text-blue-700', // anchor/link classes
bold: 'font-medium', // bold/strong classes
italic: 'font-italic', // italic/em classes
},
}
// Applying classes directly to elements
convertSchemaToHtml(richTextResponse, options)
<!-- Output: -->
<h1 class="mb-4 text-2xl md:text-4xl">Groceries</h1>
<p class="mt-3 text-lg">
Here is my shopping list for various fruit to buy at
<a
href="https://grocerystore.com"
class="underline text-blue-500 hover:text-blue-700"
>
The Grocery Store
</a>
</p>
<ol class="my-3 ml-3 flex flex-col gap-y-2">
<li class="text-sm md:text-base">apples</li>
<li class="text-sm md:text-base">oranges</li>
<li class="text-sm md:text-base">bananas</li>
</ol>
...
By utilizing this and a React/Hydrogen component developers can easily set a list of default Tailwind classes for each element. They can then add props to override a certain elements classes for easy reuse throughout their codebase.
import { convertSchemaToHtml } from '@thebeyondgroup/shopify-rich-text-renderer'
...
export default RichTextToHTML({richText, paragrpahClasses, boldCasses}){
const p = paragraphClasses ?? 'mt-3 text-lg'
const bold = boldClasses ?? 'font-medium'
const options = {
scoped: false,
classes: {
p,
bold
},
}
return (
<>
<div
className="html"
dangerouslySetInnerHTML={{
__html: convertSchemaToHtml(richText, options),
}}
/>
<div>
</>
)
}