Photo by Victoriano Izquierdo on Unsplash

How to Write Your Own Option Selector with React

In this article, I want to tell you how to write your own OptionSelector like a Checkbox, Toggle Button or Combobox.

Yesterday I wanted to try some UI development about responsive typography. I find different kinds of solutions, like media-query, viewport-based, or fluid responsive mechanics. But how can I display three of them on one screen?

The solution is not to display all the mechanics on the same screen. You give users options to select which they want.

Responsive Typography Info Screen

It's the same behavior Checkbox, ToggleButton, Combobox, etc.… In the background, you hold a state and then render according to state;

  • Default
  • Selected
  • Hover

First of all, I want to show you, How OptionSelector works. Below the link, you can try the component.

https://onurdayibasi.dev/option-selector

React Part

I need a component that has

  • Selected value,
  • Options which includes value and text array
  • and onSelect callback handler when users click other option
Define Option Selector Component

Our component has two parts one is JS (Mechanic) the other is Styling (SCSS/CSS)

In the JS part, the component renders options. But if the option sign with selected, we must display it differently. In code check, the value is selected, then add a class selected and add check icon

OptionSelector JavaScript Part

The other part is styling. Option-Selector is container styling that holds all options. An option has different modes;

  • Default Mode: default
  • Selected Mode: &.selected
  • Hover Mode: &: hover
OptionSelector Styling Part

At last, you need to hold user selection preferences where you want (Component State, Redux, LocalStorage, Backend, etc..) So write and handler and manage with projects state management mechanism

handleModeChange , handle onSelect..

Let's continue reading 😃

You can find similar samples and writings at this link. If you like this story. Please 👏👏 and share

--

--

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