Answer the question
In order to leave comments, you need to log in
Normal ToogleButton in React. How?
Hello. Please tell me how to solve the following problem.
If we write a stateless button with the pressed property, then it cannot be used independently because someone must pass this property to it.
If we write a statefull button with the pressed state, then this state cannot be changed from the outside.
Like it or not, it turns out some kind of UG with extremely dubious prospects for reuse.
Answer the question
In order to leave comments, you need to log in
You can use a native hidden checkbox . It can be used both as a controlled and as an independent element. Listen to onChange or use ref . You can style it for anything. To work, you must use the label element .
I think this is the most versatile and optimal option for this task.
Example using StyledComponents :
import * as React from 'react';
import styled from 'styled-components';
const Wrapper = styled.label`
position: relative;
display: inline-block;
width: 40px;
height: 24px;
`;
const Input: any = styled.input`
display: none;
`;
const Slider = styled.div`
position: absolute;
cursor: pointer;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: #ccc;
transition: .2s;
border-radius: 34px;
&:before {
position: absolute;
content: "";
height: 22px;
width: 22px;
left: 1px;
bottom: 1px;
background-color: white;
transition: .2s;
border-radius: 50%;
}
${Input}:checked + & {
background-color: ${props => props.theme.someColor1};
}
${Input}:focus + & {
box-shadow: 0 0 1px ${props => props.theme.someColor2};
}
${Input}:checked + &:before {
transform: translateX(16px);
}
`;
interface Props = {
name?: string
checked?: boolean
onChange?: Function
innerRef?: Function
className?: string
}
const ToggleSwitch = ({ innerRef, checked, onChange, className, name }: Props) => {
return (
<Wrapper className={className}>
<Input
innerRef={innerRef}
checked={checked}
onChange={onChange}
name={name}
type="checkbox"
/>
<Slider />
</Wrapper>
);
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question