Simone Poggi
Simone Poggi

Reputation: 1468

Convert this function to a stateless react component

I have this function that dims the trailing zero of a number, after the '.'

ex.

the final html generated by this function is something like

123.456 <span class="trailing-zeros"> 000 </span>

this is the actual code

// Only fade trailing zeros if they are decimals
function fadeTrailingZeros (val) {
  var str = val + ''
  if (str.match(/\./)) {
    return str.replace(/(0+)$/g, '<span class="trailing-zeros">' + '$1' + '</span>')
  } else {
    return str
  }
}

the regexp replaces the trailing zeros with a classified span and works wonders.

Now I have to use this in a react environment and this is a perfect case for a presentational/dumb/stateless component.

import React from 'react'

export default function fadeTrailingZeros ({ value }) {
  if (value.match(/\./)) {
    const [prec, dec] = value.split('.')
    const trailing = dec.replace(
      /(0+)$/g, 
      <span className='trailing-zeros'>{ $1 }</span>
      // ...woops! this cannot work with jsx since it's not a string 
      // to replace stuff into and $1 does mean nothing in there
    )
    return (<span>{value}.{trailing}</span>)
  } else {
    return (
      <span>{value}</span>
    )
  }
}

how could I handle that?

Upvotes: 2

Views: 196

Answers (1)

Constantin Harabara
Constantin Harabara

Reputation: 423

You where close, and already understood that you can't make JSX by concatenating strings (actually you can by involving dangerouslySetInnerHTML, but that's another topic)

Something like that should work for you, but you can certainly optimize it

const FadeTrailingZeros = ({ value }) => {
  if (value.match(/\./)) {
    let [prec, dec] = value.split('.')
    const trailingZeros = dec.match(/(0+)$/g)
    dec = dec.replace(/(0+)$/g, '')
    return (<span>{prec}.{dec}{trailingZeros && <span className='trailing-zeros'>{trailingZeros[0]}</span>}</span>)
  } else {
    return (
      <span>{value}</span>
    )
  }
}

Upvotes: 4

Related Questions