Custom data-attribute syntax error in Portable Text annotation component
annotationfor 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>
}29:43 error Parsing error: Unexpected token, expected "..."This isn't a dumb question at all! The issue you're running into is actually a JSX syntax error, not specific to Sanity's Portable Text.
The problem is that you can't use string interpolation to create JSX attributes like {customAttribute}. In JSX, you need to pass attributes as actual properties, not as strings.
Here's the corrected code:
customLink: ({ mark, children }) => {
const { dataAttribute, attributeValue } = mark
// Create a dynamic attribute object
const customAttributes = (dataAttribute && attributeValue)
? { [`data-${dataAttribute}`]: attributeValue }
: {}
return (
<span {...customAttributes} className="rainbow">
{children}
</span>
)
}What's happening here:
- You're creating an object with a computed property name using
[data-${dataAttribute}] - Then you're spreading that object into the
<span>element using{...customAttributes} - This properly passes the attribute to React/JSX
Alternatively, if you always want to add the data attribute (even if empty), you can do:
customLink: ({ mark, children }) => {
const { dataAttribute, attributeValue } = mark
return (
<span
{...(dataAttribute && attributeValue && { [`data-${dataAttribute}`]: attributeValue })}
className="rainbow"
>
{children}
</span>
)
}The key takeaway: In JSX, you can't pass HTML attributes as strings. You need to either use the spread operator with an object ({...obj}) or pass individual props directly.
Show original thread22 replies
Was this answer helpful?
Sanity – Build the way you think, not the way your CMS thinks
Sanity is the developer-first content operating system that gives you complete control. Schema-as-code, GROQ queries, and real-time APIs mean no more workarounds or waiting for deployments. Free to start, scale as you grow.