What is @radix-ui/react-toggle?
@radix-ui/react-toggle is a React component library that provides accessible and customizable toggle buttons. It is part of the Radix UI suite, which focuses on providing unstyled, accessible components that can be easily styled to fit any design system.
What are @radix-ui/react-toggle's main functionalities?
Basic Toggle Button
This code demonstrates a basic toggle button using the @radix-ui/react-toggle package. The Toggle.Root component is the container, and the Toggle.Thumb component represents the toggle switch.
import * as Toggle from '@radix-ui/react-toggle';
function App() {
return (
<Toggle.Root>
<Toggle.Thumb />
</Toggle.Root>
);
}
export default App;
Controlled Toggle Button
This code demonstrates a controlled toggle button where the toggle state is managed by a React useState hook. The pressed prop is used to control the toggle state, and the onPressedChange prop is used to update the state.
import * as Toggle from '@radix-ui/react-toggle';
import { useState } from 'react';
function App() {
const [isToggled, setIsToggled] = useState(false);
return (
<Toggle.Root pressed={isToggled} onPressedChange={setIsToggled}>
<Toggle.Thumb />
</Toggle.Root>
);
}
export default App;
Custom Styled Toggle Button
This code demonstrates how to apply custom styles to the toggle button using CSS classes. The className prop is used to add custom styles to the Toggle.Root and Toggle.Thumb components.
import * as Toggle from '@radix-ui/react-toggle';
import './App.css';
function App() {
return (
<Toggle.Root className="custom-toggle">
<Toggle.Thumb className="custom-thumb" />
</Toggle.Root>
);
}
export default App;
Other packages similar to @radix-ui/react-toggle
react-toggle
react-toggle is a widely-used package for creating toggle buttons in React. It provides a simple API and comes with default styles that can be customized. Compared to @radix-ui/react-toggle, react-toggle is more opinionated in terms of styling but is easier to set up for basic use cases.
rc-switch
rc-switch is a React component for creating switch toggles. It is part of the rc-components suite and offers a highly customizable and accessible toggle switch. Compared to @radix-ui/react-toggle, rc-switch provides more built-in styles and is more feature-rich, but it may require more effort to integrate into a custom design system.
react-switch
react-switch is another popular package for creating toggle switches in React. It offers a simple and flexible API with built-in styles that can be easily customized. Compared to @radix-ui/react-toggle, react-switch is more focused on providing a quick and easy solution for toggle switches with less emphasis on accessibility and customization.