Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
25
rated 0 times [  28] [ 3]  / answers: 1 / hits: 5134  / 3 Years ago, wed, january 13, 2021, 12:00:00

How can I add text inside a Switch component in ReactJS? I am trying to add EN and PT text inside the Switch Component.


I'm not using any lib, I built the component with only css, because I needed it to have this specific customization, so I found it easier to do with css.


I put my project into codesandbox


enter




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;
}




Thank you very much for any help!!


More From » html

 Answers
9

Take a look at my fork of your sandbox.
First of all, I moved the <input> into the <label> so it doesn't require the id/htmlFor structure that would break due to duplicate id's once you use multiple switches.


The text spans are now in their own div inside the label. They each have 50% width, are aligned to the left and right edges respectively and use flexbox to center their contents.


Depending on the width of the white area in either state of the checkbox, you might want to change the spans' width to center the text correctly. Also, the label texts can be moved to a property for reusability.


[#1970] Friday, January 8, 2021, 3 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
tyreek

Total Points: 421
Total Questions: 115
Total Answers: 102

Location: Marshall Islands
Member since Mon, May 31, 2021
3 Years ago
tyreek questions
Mon, Jul 19, 21, 00:00, 3 Years ago
Tue, Mar 23, 21, 00:00, 3 Years ago
Sat, May 16, 20, 00:00, 4 Years ago
Sun, Apr 26, 20, 00:00, 4 Years ago
;