Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

119
Vistas
Convert this function to a stateless react component

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

ex.

  • 123.456000 -> 123.456000
  • 100.0000 -> 100.0000
  • 456.999990 -> 456.999990
  • 333 -> 333

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?

over 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

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>
    )
  }
}
over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda