Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

118
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda