- Creating a custom toggle button in React with CSS variables for dynamic styling involves a similar approach to the custom checkbox and radio button. Here's how you can create a custom toggle button component.
- In your global CSS file (e.g., `App.css`), define the CSS variables for your toggle button:
:root {
--toggle-width: 200px;
--toggle-height: 25px;
--toggle-off-bg-color: green;
--toggle-on-bg-color: yellow;
--toggle-circle-color: red;
--toggle-circle-size: 21px;
--toggle-circle-offset: 2px;
}
- Create a React component (`CustomToggleButton.js`) for the toggle button. This component will manage its own state and use props to notify the parent component about the change:
import React, { useState } from 'react';
import './App.css'; // Make sure to import the CSS where you've defined your variables
const CustomToggleButton = ({ onChange }) => {
const [isEnabled, setIsEnabled] = useState(false);
const toggleEnabled = () => {
setIsEnabled(!isEnabled);
onChange(!isEnabled);
};
return (
<div className={`toggle-container ${isEnabled ? 'enabled' : ''}`} onClick={toggleEnabled}>
<div className="toggle-circle"></div>
</div>
);
};
export default CustomToggleButton;
- Add the necessary styles in `App.css` to use the CSS variables. Make sure to style both the container and the circle to reflect the toggle state:
.toggle-container {
width: var(--toggle-width);
height: var(--toggle-height);
background-color: var(--toggle-off-bg-color);
border-radius: var(--toggle-height);
cursor: pointer;
transition: background-color 0.2s;
display: flex;
align-items: center;
padding: var(--toggle-circle-offset);
}
.toggle-container.enabled {
background-color: var(--toggle-on-bg-color);
}
.toggle-circle {
width: var(--toggle-circle-size);
height: var(--toggle-circle-size);
background-color: var(--toggle-circle-color);
border-radius: 50%;
transition: transform 0.2s;
}
.toggle-container.enabled .toggle-circle {
transform: translateX(calc(var(--toggle-width) - var(--toggle-circle-size) - (2 * var(--toggle-circle-offset))));
}
- Finally, you can use your `CustomToggleButton` component within your app. Pass an `onChange` prop to handle changes:
import React from 'react';
import CustomToggleButton from './CustomToggleButton';
function App() {
const handleToggleChange = (isEnabled) => {
console.log('Toggle is now: ', isEnabled ? 'Enabled' : 'Disabled');
};
return (
<div className="App">
<CustomToggleButton onChange={handleToggleChange} />
</div>
);
}
export default App;
- Users can override the CSS variables in their styles to customize the toggle button:
:root {
--toggle-on-bg-color: #FF5722;
/* Change the on-state background color */
--toggle-off-bg-color: #ccc;
/* Change the off-state background color */
}
- This approach allows you to create a flexible and customizable toggle button in React, with dynamic styling controlled through CSS variables.
No comments:
Post a Comment