Guide on inserting text within a Toggle Switch Component using React

Is there a way to insert text inside a Switch component in ReactJS? Specifically, I'm looking to add the text EN and PT within the Switch Component.

I opted not to use any libraries for this. Instead, I crafted the component solely using CSS to achieve the desired customization, as I found it easier to implement with CSS.

You can check out my project on codesandbox

https://i.sstatic.net/vp1Cb.png

import React from "react";
import "./switch.css";

const Switch = ({ isOn, handleToggle, onColor }) => {
  return (
    <>
      <input
        checked={isOn}
        onChange={handleToggle}
        className="react-switch-checkbox"
        id={`react-switch-new`}
        type="checkbox"
      />
      <label
        style={{ background: isOn && onColor }}
        className="react-switch-label"
        htmlFor={`react-switch-new`}
      >
        <span className={`react-switch-button`} />
      </label>
    </>
  );
};

export default Switch;
.react-switch-checkbox {
  height: 0;
  width: 0;
  visibility: hidden;
}

.react-switch-label {
  display: flex;
  align-items: center;
  justify-content: space-between;
  cursor: pointer;
  width: 100px;
  height: 50px;
  background: #fff;
  position: relative;
  transition: background-color 0.2s;
}

.react-switch-label .react-switch-button {
  content: "";
  position: absolute;
  top: 2px;
  left: 2px;
  width: 45px;
  height: 45px;
  transition: 0.2s;
  background: #000;
  box-shadow: 0 0 2px 0 rgba(10, 10, 10, 0.29);
}

.react-switch-checkbox:checked + .react-switch-label .react-switch-button {
  left: calc(100% - 2px);
  transform: translateX(-100%);
}

.react-switch-label:active .react-switch-button {
  width: 60px;
}

Your assistance is highly appreciated!

Answer №1

Check out the modifications I made to your sandbox version. In my updated version, I repositioned the <input> element within the <label> to eliminate the need for the id/htmlFor structure that becomes problematic when using multiple switches with duplicate ids.

The individual text spans are now housed in separate div elements inside the label. Each span occupies 50% width and is aligned to either the left or right edge while utilizing flexbox for content centering.

To ensure proper text alignment within the white area of each checkbox state, you may need to adjust the spans' widths accordingly. Additionally, consider moving the label texts to a property for improved reusability.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best approach to incorporate this feature in a React application?

I am planning to create a webzine website using React. I am looking to achieve the functionality where clicking on the index button will enlarge the box size and reveal a hidden menu bar, similar to the images below. https://i.stack.imgur.com/S4kUg.png ...

What's the best way to search through various addresses for the source in an image tag?

In my current Laravel 5.8 project, I am faced with the task of searching through three different image sources for an img tag. First, I attempt to load the image from "". If that fails, I try a second URL like "". Should both attempts be unsuccessful, I th ...

Creating a gradient background with the makeStyles function

Why is it that the background: 'linear-gradient(to right, blue.200, blue.700)' doesn't work within makeStyles? I just want to add a gradient background to the entire area. Do you think <Container className={classes.root}> should be rep ...

I need to prevent form submission when the submit button is clicked. How can I achieve this?

I'm currently developing a web application using ASP.net. Within the form, there is a submit button that has the following code: <input type='submit' value='submit request' onclick='btnClick();'>. The desired func ...

Steps to open and configure a Mobile-Angular modal from another controller

Is it possible to use a modal in Angular JS for mobile devices without compromising the layout? I'm having trouble setting up the controller for my modal inside my main controller and passing parameters. Should I consider using ui-bootstrap for this p ...

Using Material UI makeStyles in a TypeScriptX Class Component

Is it possible to utilize Material UI styling options within a TSX class-component? I'm facing challenges due to Typed Props and State and need guidance on how to achieve this. My code is throwing an "Invalid hook" error in the componentWillMount meth ...

Displaying a background image in Laravel using the storage directory

Can anyone offer some guidance on how to load a background image from storage? I have tried using the following code with normal img src, but it doesn't seem to work with background images. background-image: url({{ Storage::get("{$post->image}") } ...

Received a syntax error from the DOM parser even after successfully downloading it through NPM

Seeking guidance as a beginner in this technology field. I have installed dom-parser from the NPM package. However, when I tried to declare it below, I encountered a syntax error. Although it seems like a minor issue, I am puzzled and unsure of where I am ...

The design of iOS7 Safari becomes distorted when the orientation changes and an input field is in focus

It appears that there is a major issue in iOS7 on iPhone and iPad devices, and possibly on other versions as well. When you focus on an input field, causing the keyboard to open, the layout experiences a severe and irreversible disruption upon changing or ...

I am unable to halt the relentless stream of asynchronous events

Struggling to retrieve an array using a loop in the asynchronous environment of nodejs. Check out my code below: getDevices(userIDs, function(result) { if (result) { sendNotification(messageUser, messageText, result); res.send("Success"); } else { ...

Typescript: Ways to fix the error 'rxjs/Rx does not have any exported member 'SubscriptionLike'

I'm attempting to replicate the steps outlined in this tutorial found here https://www.youtube.com/watch?v=gxCu5TEmxXE. However, upon running tsc -p, I encounter an error. Is there a specific import that I am missing? ERROR: node_modules/@angular/co ...

The AJAX data variable fails to send to PHP script although $_POST is defined

I am at my wit's end with this problem. I am attempting to send a variable to a PHP script using AJAX, and although I can confirm that $_POST is set, the variable remains undefined. Oddly enough, I have used almost the same code in other instances an ...

jQuery breaks when working with ASP.NET forms

Essentially, it appears that using an ASP.NET page with the <form runat=server> tag can cause some jQuery scripts to break. To illustrate this issue, consider the following scenario: You have a simple webpage with only a checkbox, like so: <inpu ...

Automatic Email Reply that Automatically populates the recipient field with the sender's information

I'm curious to know if it's possible to create a mailto link that automatically populates the TO: field with the email of the original sender, without including the email address in the link itself. For instance: "a href="mailto:ORIGINALSENDER? ...

Highcharts: single point muted and not easily seen when markers are turned off

Highchart displaying data with some null points (only visible via tooltip if marker disabled): https://i.stack.imgur.com/u04v1.png https://i.stack.imgur.com/uRtob.png Enabling markers will resolve the issue of invisible points, but it may look cluttered ...

Using an aria-label attribute on an <option> tag within a dropdown menu may result in a DAP violation

Currently, I am conducting accessibility testing for an Angular project at my workplace. Our team relies on the JAWS screen reader and a helpful plugin that detects UI issues and highlights them as violations. Unfortunately, I've come across an issue ...

"Encountering issue with SCSS variable not being applied to background in file

$enable-grid-classes: false; $enable-cssgrid:true; $deepBlue: #032f3e; body { --bs-body-bg: orange ; } @import "https://fonts.googleapis.com/css2?family=Space+Grotesk:<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="463121 ...

JavaScript causing values to disappear when the page refreshes

When a user hovers over ImageButtons, I use Javascript to change the ImageUrl. However, on submitting the form, the updated ImageUrl property is not reflected in the code behind. Similarly, I also dynamically update a span tag using Javascript, but its alt ...

Changing the PublicPath of Create React App in a development environment: A step-by-step guide

I'm currently utilizing Microsoft.DotNet.Web.Spa.ProjectTemplates::2.0.0-rc1-final, which leverages Create-react-app and AspnetCore.ReactDevelopmentServer internally. Within my development environment, I am using IIS to host multiple APIs - api1 at h ...

Increase the spacing between the dropdown menu and the first option

I am attempting to create some space between the select box and the dropdown list. An example image can be seen below: https://i.sstatic.net/CovTn.png In the top example, a div was used. Despite trying padding and margins, I did not achieve the desired ...