Slate leaves: Any simple example?

default discord avatar
jakey___
6 months ago
14

I keep seeing examples that kind of go half-way to what I need when it comes to adding a custom slate leaf.



All I want to do is add some buttons to the editor that are for changing the color of the text.



I think I understand the "leaf" portion of the config, but not the "button" one. Any help welcome!



As I continue digging into this, I think what I want is a custom element instead, but the config looks similar so my question is still relevant.



ok, think my realization of needing to use an element in my use-case led me to a good example



https://github.com/payloadcms/public-demo/tree/master/src/fields/richText/largeBody


that seemed to get me closer, but it appears that that implementation assumes you want a block level element. not inline like my current-use-case



switching it to a leaf seems to have more of the effect i'm wanting. however, I don't see the way you adjust the preview in payload just yet..



Finally got it.



i'll try and condense what i did...



index.scss

.terminaltext-leaf-traversal {
    color: yellow;
}


index.tsx

import React from 'react'
import { LeafButton } from 'payload/components/rich-text'

import './index.scss'

const baseClass = 'terminaltext-leaf-traversal'
const name = 'terminal-text-traversal'

const Button = () => (
    <LeafButton format={name}>
        Traversal
    </LeafButton>
)

const Leaf = ({ attributes, leaf, children }) => {
    if (leaf[name]) {
        return <span {...attributes} className={baseClass}>{children}</span>
    }
    return <span {...attributes}>{children}</span>
}

export default {
    name,
    Button,
    Leaf,
}


The key thing I missed at the end was the fact that the name needed to be consistent between the button's 'format' attribute and the leaf's 'name' property check.



the examples I saw had a lot of nesting folder structure involved but if you wanted to do something simple like me, this will probably get you by.



You then add this leaf to your richText admin.leaves array and you'll be able to style the text you want to be 'yellow' or whatever you like.



Hope someone finds this useful!



to add on to clarify, the way you'd use the above code is you add the exported object to the

leaves

array of a

richText

field. So if the new leaf was called

customLeaf

it might look like this



{
    name: 'somet_field',
    type: 'richText',
    admin: {
        elements: [],
        leaves: ['bold', 'italic', 'strikethrough', 'underline', 'code', customLeaf,],
    },
}


thanks @plainnn for helping improve this example!

    Open the post
    Continue the discussion in Discord
    Like what we're doing?
    Star us on GitHub!

    Star

    Connect with the Payload Community on Discord

    Discord

    online

    Can't find what you're looking for?

    Get help straight from the Payload team with an Enterprise License.