Pen Settings

HTML

CSS

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URL's added here will be added as <link>s in order, and before the CSS in the editor. If you link to another Pen, it will include the CSS from that Pen. If the preprocessor matches, it will attempt to combine them before processing.

+ add another resource

JavaScript

Babel is required to process package imports. If you need a different preprocessor remove all packages first.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Behavior

Save Automatically?

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

Format on Save

If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.

Editor Settings

Code Indentation

Want to change your Syntax Highlighting theme, Fonts and more?

Visit your global Editor Settings.

HTML

              
                <div id="root"></div>
              
            
!

CSS

              
                
              
            
!

JS

              
                const CURRENCY_JSON_URL = 'https://raw.githubusercontent.com/umpirsky/currency-list/master/data/en/currency.json';

const DEFAULT_OPTION = 'default';

const DISCOUNT_PERCENT = 0.05;

const locales = {
  af:	'Afrikaans',
  sq:	'Albanian',
  am:	'Amharic',
  ar:	'Arabic',
  hy:	'Armenian',
  az:	'Azerbaijan',
  ba:	'Bashkir',
  eu:	'Basque',
  be:	'Belarusian',
  bn:	'Bengali',
  bs:	'Bosnian',
  bg:	'Bulgarian',
  my:	'Burmese',
  ca:	'Catalan',
  ceb:	'Cebuano',
  zh:	'Chinese',
  hr:	'Croatian',
  cs:	'Czech',
  da:	'Danish',
  nl:	'Dutch',
  en:	'English',
  eo:	'Esperanto',
  et:	'Estonian',
  fi:	'Finnish',
  fr:	'French',
  gl:	'Galician',
  ka:	'Georgian',
  de:	'German',
  el:	'Greek',
  gu:	'Gujarati',
  ht:	'Haitian (Creole)',
  he:	'Hebrew',
  mrj:	'Hill Mari',
  hi:	'Hindi',
  hu:	'Hungarian',
  is:	'Icelandic',
  id:	'Indonesian',
  ga:	'Irish',
  it:	'Italian',
  ja:	'Japanese',
  jv:	'Javanese',
  kn:	'Kannada',
  kk:	'Kazakh',
  km:	'Khmer',
  ko:	'Korean',
  ky:	'Kyrgyz',
  lo:	'Laotian',
  la:	'Latin',
  lv:	'Latvian',
  lt:	'Lithuanian',
  lb:	'Luxembourgish',
  mk:	'Macedonian',
  mg:	'Malagasy',
  ms:	'Malay',
  ml:	'Malayalam',
  mt:	'Maltese',
  mi:	'Maori',
  mr:	'Marathi',
  mhr:	'Mari',
  mn:	'Mongolian',
  ne:	'Nepali',
  no:	'Norwegian',
  pap:	'Papiamento',
  fa:	'Persian',
  pl:	'Polish',
  pt:	'Portuguese',
  pa:	'Punjabi',
  ro:	'Romanian',
  ru:	'Russian',
  gd:	'Scottish',
  sr:	'Serbian',
  si:	'Sinhala',
  sk:	'Slovakian',
  sl:	'Slovenian',
  es:	'Spanish',
  su:	'Sundanese',
  sw:	'Swahili',
  sv:	'Swedish',
  tl:	'Tagalog',
  tg:	'Tajik',
  ta:	'Tamil',
  tt:	'Tatar',
  te:	'Telugu',
  th:	'Thai',
  tr:	'Turkish',
  udm:	'Udmurt',
  uk:	'Ukrainian',
  ur:	'Urdu',
  uz:	'Uzbek',
  vi:	'Vietnamese',
  cy:	'Welsh',
  xh:	'Xhosa',
  yi:	'Yiddish',
};

const rtlLocales = [ 'ar', 'fa', 'he', 'ml', 'pa', 'ur', 'yi' ];

const cartItems = [
  {id: 1, key: 'apple_watch', quantity: 17, pricePerItem: 12300},
  {id: 2, key: 'grocery_bag', quantity: 1, pricePerItem: 456},
  {id: 3, key: 'tesla_s', quantity: 2, pricePerItem: 13300000},
];

function Header() {
  return (
    <h2 className="is-size-4" style={{marginBottom: '0.25em'}}>Cart &amp; Checkout Demo</h2>
  );
}

function FormField({ labelText, renderControl, renderHelpText }) {
  return (
    <div className="columns is-mobile">
      <div className="column is-2">
        <label
          className="label"
          style={{paddingTop: '0.35rem'}}
        >
          {labelText}
        </label>
      </div>

      <div className="column">
        <div className="control">{renderControl()}</div>
        
        {renderHelpText && 
          <p className="help" style={{marginTop: 0}}>{renderHelpText()}</p>
        }
      </div>
    </div>
  );
}

function LocaleSwitcher({ selectedLocale, onLocaleSwitched }) {
  function handleChange(event) {
    event.preventDefault();
    
    onLocaleSwitched(event.target.value);
  }
  
  return (
    <FormField
      labelText="Locale"
      
      renderControl={() => (
        <div className="select">
          <select value={selectedLocale} onChange={handleChange}>
            {Object.keys(locales).map(code => (
              <option value={code} key={code}>{locales[code]}</option>
            ))}
          </select>
        </div>
      )}
      
      renderHelpText={() => (
        <>
          Translation powered by{' '}
          <a href="http://translate.yandex.com" target="_blank">Yandex.Translate</a>
        </>
      )}
    />
  );
}

function CurrencySwitcher({ selectedCurrency, onCurrencySwitched }) {
  const [currencies, setCurrencies] = React.useState({});
  
  React.useEffect(() => {
    fetch(CURRENCY_JSON_URL)
      .then(response => response.json())
      .then(json => setCurrencies(json));
  }, [currencies]);
  
  function handleChange(event) {
    event.preventDefault();
    
    onCurrencySwitched(event.target.value);
  }
  
  const currencyCodes = Object.keys(currencies);
  
  const isLoading = currencyCodes.length === 0;
  
  return (
    <FormField
      labelText="Currency"
      
      renderControl={() => (
        <div className={`select ${isLoading? `is-loading` : ''}`}>
          <select value={selectedCurrency} onChange={handleChange}>
            {isLoading
             
              ? <option value="">Loading</option>
             
              : 
              currencyCodes.map((code) => (
                <option value={code} key={code}>
                  {currencies[code]}
                </option>
              ))  
            }
          </select>
        </div>
      )}
      
      renderHelpText={() => (
        <>
          This is just a formatting change, no currency conversion happens
        </>
      )}
    />
  );
}

function NumberSystemSwitcher({ selectedNumberSystem, onNumberSystemSwitched }) {
  function handleChange(event) {
    event.preventDefault();
    
    onNumberSystemSwitched(event.target.value);
  }
  
  return (
    <FormField
      labelText="Number system"
      
      renderControl={() => (
       <div className="select">
          <select value={selectedNumberSystem} onChange={handleChange}>
            <option value={DEFAULT_OPTION}>From locale</option>
            <option value="latn">Western Arabic</option>
            <option value="arab">Eastern Arabic</option>
            <option value="bali">Balinese</option>
            <option value="beng">Bengali</option>
            <option value="mymr">Burmese</option>
            <option value="hanidec">Chinese</option>
            <option value="deva">Devanagari</option>
            <option value="gujr">Gujarati</option>
            <option value="guru">Gurmukhi</option>
            <option value="knda">Kannada</option>
            <option value="khmr">Khmer</option>
            <option value="laoo">Lao</option>
            <option value="limb">Limbu</option>
            <option value="mlym">Malayalam</option>
            <option value="mong">Mongolian</option>
            <option value="orya">Oriya</option>
            <option value="tamldec">Tamil</option>
            <option value="telu">Telugu</option>
            <option value="thai">Thai</option>
            <option value="tibt">Tibetan</option>
          </select>
        </div>
      )}
      
       renderHelpText={() => (
        <>
          Overrides selected locale's default number system
        </>
      )}
    />
  );
}

function Cart({ locale, strings, currency, numberSystem }) {
  const localeWithNumberSystem = numberSystem == DEFAULT_OPTION ? 
                                                         locale :
                                `${locale}-u-nu-${numberSystem}`;
  
  const formatNumber = new Intl.NumberFormat(localeWithNumberSystem).format;
  
  const formatCurrency = new Intl.NumberFormat(
    localeWithNumberSystem,
    { style: 'currency', currency },
  ).format;
  
  const formatPercent = new Intl.NumberFormat(
    localeWithNumberSystem,
    { style: 'percent' },
  ).format;
  
  const isLocaleRTL = rtlLocales.includes(locale);
  
  function getTotal({ withDiscount } = { withDiscount: false }) {
    const totalInCents = cartItems.reduce((accumulator, current) => {
      return accumulator + current.quantity * current.pricePerItem;
    }, 0);
    
    const discountMultiplier = withDiscount ? (1 - DISCOUNT_PERCENT) : 1;
    
    return totalInCents * discountMultiplier / 100;
  }
  
  return (
     <table className="table is-striped is-fullwidth">
       <thead>
         <tr>
           <th className={isLocaleRTL ? 'has-text-right' : ''}>
             {strings['item']}
           </th>
           <th className="has-text-right">{strings['quantity']}</th>
           <th className="has-text-right">{strings['price_per_item']}</th>
          <th className="has-text-right">{strings['subtotal']}</th>
         </tr>
        </thead>

       <tbody>
        {cartItems.map(({ id, key, quantity, pricePerItem }) => (
           <tr key={id}>
             <td className={`is-size-7 ${isLocaleRTL ? 'has-text-right' : ''}`}>
               {strings[key]}
             </td>    

             <td className="has-text-right is-size-6">
               {formatNumber(quantity)}
             </td>

             <td className="has-text-right is-size-6">
               {formatCurrency(pricePerItem / 100)}
             </td>

             <td className="has-text-right is-size-6">
               {formatCurrency(pricePerItem * quantity / 100)}
             </td>
           </tr>
         ))}
       </tbody>

       <tfoot>
         <tr className="has-background-grey-lighter">
           <td
             colSpan="3"
             className={`is-size-6 ${isLocaleRTL ? 'has-text-left' : 'has-text-right'}`}
           >
              {strings['total_before_discount']}
           </td>

           <td
             className="is-size-6 has-text-right"
           >
             {formatCurrency(getTotal())}
           </td>
         </tr>

        <tr className="has-background-grey-lighter">
          <td
             colSpan="3"
             className={`is-size-6 ${isLocaleRTL ? 'has-text-left' : 'has-text-right'}`}
           >
             {strings['discount']}
          </td>

          <td className="is-size-6 has-text-right">
            {formatPercent(DISCOUNT_PERCENT)}
          </td>
         </tr>

         <tr className="has-background-grey-lighter">
           <td
             colSpan="3"
             className={`is-size-6 ${isLocaleRTL ? 'has-text-left' : 'has-text-right'}`}
           >
             <strong>{strings['total']}</strong>
           </td>

           <td className="is-size-6 has-text-right">
             <strong>{formatCurrency(getTotal({ withDiscount: true }))}</strong>
           </td>
         </tr>
       </tfoot>
    </table>
  );
}

function Message({ text }) {
  return (
    <article className="message is-info">
      <div className="message-body">
        {text}
      </div>
    </article>
  );
}

function Footer() {
  return (
    <footer className="footer">
      <div className="content has-text-centered">
        <p className="is-size-7">
          This demo is a companion to a <a href="https://phrase.com/blog/" target="_blank">Phrase</a> blog article. The behaviour of this demo may depend on your browser. Number formatting uses <code><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/NumberFormat" target="_blank">Intl.NumberFormat</a></code>.
          Built with <a href="https://reactjs.org/" target="_blank">React</a> and <a href="https://bulma.io/" target="_blank">Bulma</a>.
        </p>
      </div>
    </footer>
  );
}

function App() {
  const [locale, setLocale] = React.useState('en');
  
  const [currency, setCurrency] = React.useState('USD');
  
  const [numberSystem, setNumberSystem] = React.useState(DEFAULT_OPTION);
  
  const enStrings = {
    cart_header: 'Your Shopping Cart',
    item: 'Item',
    quantity: 'Quantity',
    price_per_item: 'Price per item',
    subtotal: 'Subtotal',
    apple_watch: 'Apple Watch Series 4 (Special Sale)',
    grocery_bag: 'Eco-friendly Grocery Bag',
    tesla_s: 'Tesla Model S',
    total_before_discount: 'Total before discount',
    discount: 'Discount',
    total: 'Total',
    checkout_header: 'Checkout',
  };
  
  const [strings, setStrings] = React.useState(enStrings);
  
  const [isLoading, setIsLoading] = React.useState(false);
  
  React.useEffect(() => {
    if (locale === 'en') {
      setStrings(enStrings);
      return;
    }
    
    setIsLoading(true);
    
    const textParams = Object
                        .values(enStrings)
                        .map(str => `text=${encodeURIComponent(str)}`)
                        .join('&');
    
    fetch(atob('aHR0cHM6Ly90cmFuc2xhdGUueWFuZGV4Lm5ldC9hcGkvdjEuNS90ci5qc29uL3RyYW5zbGF0ZT9rZXk9dHJuc2wuMS4xLjIwMjAwMzI0VDEwMjk1MVouMjY3NzBmNDYzZjBhMzQxZC40OTlhNTA3M2M4MGY4ZDQ2NjlmOWJlZTY2ZTMyZTViZmYzOGFiODBi') +   
                `&lang=en-${locale}&${textParams}`)
      .then(response => response.json())
      .then((json) => {
        const translations = json.text;

        const newStrings = {};

        Object.keys(enStrings)
              .forEach((key, index) => newStrings[key] = translations[index]);

        setStrings(newStrings);
      
        setIsLoading(false);
      });
    
  }, [locale]);
  
  React.useEffect(() => setNumberSystem(DEFAULT_OPTION), [locale]);
  
  function handleLocaleSwitched(newLocale) {
    setLocale(newLocale);
    
    setItems(cartItems[newLocale]);
  }
  
  return (
    <>
      <section className="section" style={{ paddingTop: '1rem' }}>
        <div className="container" lang={locale}>
          <Header />

          <section className="box has-background-white-ter">
              <LocaleSwitcher
                selectedLocale={locale}
                onLocaleSwitched={(newLocale) => setLocale(newLocale)}
              />

              <NumberSystemSwitcher
                selectedNumberSystem={numberSystem}
                onNumberSystemSwitched={(newNumberSystem) => setNumberSystem(newNumberSystem)}
              />

              <CurrencySwitcher
                selectedCurrency={currency}
                onCurrencySwitched={(newCurrency) => setCurrency(newCurrency)}
              />
          </section>

          {isLoading
            ? 
              <Message text="Loading..." />
            :
              <section dir={rtlLocales.includes(locale) ? 'rtl': 'ltr'}>
                 <Cart
                   locale={locale}
                   strings={strings}
                   currency={currency}
                   numberSystem={numberSystem}
                 />
              </section>
          }
        </div>
      </section>
      
      <Footer />
    </>
  );
}

ReactDOM.render(<App />, document.getElementById('root'));

              
            
!
999px

Console