Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR JAVASCRIPT

tailwind css toggle switch react

import { useState, useEffect } from 'react';
import { PropTypes } from 'prop-types';
function Switch(props) {
    const [toggle , setToggle ] = useState(false)
    const toggleClass = 'transform translate-x-12';

    const _handleClick = e => {
        props.cb()
        setToggle(!toggle);
    }

    useEffect(() => {
        setToggle(props.toggled)
    }, [props.toggled])
    return (
        //   Switch Container
        <div
            className="md:w-20 md:h-8 w-12 h-6 flex items-center bg-gray-300 rounded-full p-1 cursor-pointer"
            onClick={() => {
                _handleClick();
            }}
        >
            {/* Switch */}
            <div
                className =  {"bg-white md:w-6 md:h-6 h-5 w-5 rounded-full shadow-md transform " +  (toggle ? null : toggleClass)}
            ></div>
           
            {!toggle && (
                <span className="text-xs -translate-x-5"> {props.offValue}</span>
            )}
            {toggle  && (
                <span className='text-xs translate-x-2'>{props.onValue}</span>
            )}
            
        </div>
    );
}
Switch.PropTypes = {
    cb: PropTypes.func.isRequired,
    toggled: PropTypes.bool.isRequired,
    offValue: PropTypes.string.isRequired,
    onValue: PropTypes.string.isRequired
}
export default Switch;
 
PREVIOUS NEXT
Tagged: #tailwind #css #toggle #switch #react
ADD COMMENT
Topic
Name
9+2 =