Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

117
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!