How to prepend $ to number field for currency values in Sanity?

2 replies
Last updated: Aug 30, 2023
How would I modify the number field to prepend a $ for a currency value? For example like this:
AI Update

You can create a custom input component for your number field that prepends a $ sign. Here's how to do it:

First, create a custom input component in your Studio code:

import { NumberInputProps, set, unset } from 'sanity'

function CurrencyInput(props: NumberInputProps) {
  const { elementProps, onChange, value = 0 } = props
  
  return (
    <div style={{ display: 'flex', alignItems: 'center' }}>
      <span style={{ marginRight: '0.5rem', fontSize: '1.2em' }}>$</span>
      <input
        {...elementProps}
        type="number"
        value={value}
        onChange={(event) => {
          const nextValue = event.currentTarget.value
          onChange(nextValue ? set(parseFloat(nextValue)) : unset())
        }}
        style={{ flex: 1 }}
      />
    </div>
  )
}

Then, in your schema definition, use the Form Components API to attach this custom component to your number field:

import { defineField, defineType } from 'sanity'

export default defineType({
  name: 'product',
  type: 'document',
  fields: [
    defineField({
      name: 'price',
      type: 'number',
      title: 'Price',
      components: {
        input: CurrencyInput
      }
    })
  ]
})

This approach uses the Form Components API, which lets you create custom drop-in replacements for default form widgets. You can customize the styling to match your Studio's design system, and the component will properly handle real-time collaboration and validation.

If you want to preserve the default number input styling while just adding the $ prefix, you can use the renderDefault function to wrap the existing input:

function CurrencyInput(props: NumberInputProps) {
  return (
    <div style={{ display: 'flex', alignItems: 'center' }}>
      <span style={{ marginRight: '0.5rem', fontSize: '1.2em' }}>$</span>
      {props.renderDefault(props)}
    </div>
  )
}

For more complex currency formatting (like adding commas for thousands), you can check out the custom input component guide which covers handling value transformations and proper state management.

Show original thread
2 replies
That would be a custom component . It would be fairly simple. Use the
renderDefault
method that’s passed into your
props
and mash a little Box with a
$
in it in front of it.
awesome thanks
user M
i'll give that a go

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.

Was this answer helpful?