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

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!

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store