What Can You Do With a Single HTML Element? I Just Made a Customizable Rating Component With It

Josh Lin
2 min readMay 13, 2021

Why Single HTML Element?

  • just a fun challenge, interesting right? and yes this was my first thought, and turns out a single element can do quite a lot
screenshot of rating component with single element
  • less elements, better performance, alough most projects won’t encounter performance problem, still someone may need it
single-element(bottom left) rating vs multi-element(top right), both repeated 10,000 times (single-element react much faster and cost less resource)

How To Code It Out?

1. remove default styles of input[range]

a input of type range is pretty suitable for the rating job, for rating 1–5 stars, just like setting the range, but first we need to remove the default styles of range element

we need browser support appearance

then remove dot

we need browser support -moz-range-thumb or -webkit-scrollbar-thumb

2. create svg backgrounds

svg draw star
svg as background using data uri

more like a rating component now, next we join the pieces and make it a whole

3. build a react component

generate svg backgrounds, adjust styles, apply value and callback when change, for the full codes please refer this repo

That’s all for today, thanks!