Build a Reactjs Switch Toggle Component
Renders a toggle component.
- Use the
useState()
to initialize theisToggleOn
state variable tofalse
. - Use an object,
style
, to hold the styles for individual components and their states. - Return a
<button>
that alters the component'sisToggledOn
when itsonClick
event is fired and determine the appearance of the content based onisToggleOn
, applying the appropriate CSS rules from thestyle
object.
function Toggle(props) {
const [isToggleOn, setIsToggleOn] = React.useState(false);
const style = {
on: {
backgroundColor: "green",
},
off: {
backgroundColor: "grey",
},
};
return (
<button
onClick={() => setIsToggleOn(!isToggleOn)}
style={isToggleOn ? style.on : style.off}
>
{isToggleOn ? "ON" : "OFF"}
</button>
);
}
ReactDOM.render(<Toggle />, document.getElementById("root"));
Live Demo

You like our Content? Follow us to stay up-to-date.