Go Behind the Experience to see how Tecovas brings the West to life with Sanity 🤠 July 18th

Issue with creating a custom annotation in Portable Text in JavaScript.

22 replies
Last updated: May 7, 2020
this is probably a dumb JS question, but i'm running into an issue while trying to create my own custom
annotation
for Portable Text.
i'm attempting to create my own data-attribute, and the content is passing in just fine, but when i try to add it to my mark, it just errors out.

here's my code:

customLink: ({ mark, children}) => {
      const { dataAttribute, attributeValue } = mark
      const customAttribute = (dataAttribute && attributeValue) ? `data-${dataAttribute}="${attributeValue}"` : ''
      
      return <span {customAttribute} className={`rainbow`} >{children}</span>
    }
and the error is
29:43  error  Parsing error: Unexpected token, expected "..."
May 7, 2020, 3:06 PM
i tried adding the spread
...
but that causes a different error
May 7, 2020, 3:07 PM
so how do i pass this variable into my return?
May 7, 2020, 3:07 PM
which line is line 29?
May 7, 2020, 3:07 PM
user S
its the return
May 7, 2020, 3:08 PM
it doesn't like the
{customAttribute}
May 7, 2020, 3:08 PM
ah!
May 7, 2020, 3:09 PM
try something like this:
May 7, 2020, 3:15 PM
const customLink = ({ mark, children }) => { 
    const { dataAttribute, attributeValue } = mark
    const attribute = { [dataAttribute]: attributeValue };
    return (
        <span {...attribute} className='rainbow'>{children}</span>
    );
};   
May 7, 2020, 3:16 PM
that works to clear the error, but doesn't return my desired output...
returns
toggle="wonderful-things"

want
data-toggle="wonderful-things"
May 7, 2020, 3:20 PM
so just need to add the
data-
prefix
May 7, 2020, 3:20 PM
ah ok 1 sec
May 7, 2020, 3:22 PM
something like this:
May 7, 2020, 3:22 PM
const customLink = ({ mark, children }) => { 
    const { dataAttribute, attributeValue } = mark
    const attribute = { ['data-'+dataAttribute]: attributeValue };
    return (
        <span {...attribute} className='rainbow'>{children}</span>
    );
};    
May 7, 2020, 3:22 PM
that works a treat! thank you! 🙏
May 7, 2020, 3:23 PM
awesome! :party_parrot:
May 7, 2020, 3:23 PM
for future reference, what was i doing incorrectly?
May 7, 2020, 3:23 PM
I think you needed to convert it to a key:value object to spread it
May 7, 2020, 3:25 PM
that makes sense...
May 7, 2020, 3:25 PM
still find it odd that just the regular
{var}
way wasn't working
May 7, 2020, 3:26 PM
yeah, in react it wants a thing, and then wants to attach a value/property to said thing
May 7, 2020, 3:26 PM
I dont think it’s like PHP where you can just echo out values
May 7, 2020, 3:26 PM
(ie a string)
May 7, 2020, 3:26 PM

Sanity– build remarkable experiences at scale

Sanity is a modern headless CMS that treats content as data to power your digital business. Free to get started, and pay-as-you-go on all plans.

Was this answer helpful?