Enbabling Light and Dark Mode
How to implement light and dark mode in React.js using a simple button and the useState hook. By dynamically updating inline styles, we can easily switch the appearance of a Bootstrap accordion without using any external library. This approach is beginner-friendly and perfect for understanding theme toggling in React.
Features of the Updated React State Code
Full Code:-
import React, { useState } from "react";
export default function About() {
const [light_style, dark_style] = useState({
color: "black",
backgroundColor: "white",
});
const [btn_text, new_btn_text] = useState("Enable Dark Mode")
let toggle_Btn = () => {
if (light_style.color === "black") {
dark_style({
color: "white",
backgroundColor: "black",
border: '1px solid white'
});
new_btn_text("Enable Light Mode")
} else {
dark_style({
color: "black",
backgroundColor: "white",
});
new_btn_text("Enable Dark Mode")
}
};
return (
<div className="container my-3" style={light_style}>
<h1 className="my-3">About us</h1>
<div className="accordion" id="accordionExample">
<div className="accordion-item" style={light_style}>
<h2 className="accordion-header">
<button
className="accordion-button" style={light_style}
type="button"
data-bs-toggle="collapse"
data-bs-target="#collapseOne"
aria-expanded="true"
aria-controls="collapseOne"
>
Accordion Item #1
</button>
</h2>
<div
id="collapseOne"
className="accordion-collapse collapse show"
data-bs-parent="#accordionExample"
>
<div className="accordion-body">
<strong>This is the first itemβs accordion body.</strong> It is
shown by default, until the collapse plugin adds the appropriate
classes that we use to style each element.
<code>.accordion-body</code>
</div>
</div>
</div>
<div className="accordion-item" style={light_style}>
<h2 className="accordion-header">
<button
className="accordion-button collapsed" style={light_style}
type="button"
data-bs-toggle="collapse"
data-bs-target="#collapseTwo"
aria-expanded="false"
aria-controls="collapseTwo"
>
Accordion Item #2
</button>
</h2>
<div
id="collapseTwo"
className="accordion-collapse collapse"
data-bs-parent="#accordionExample"
>
<div className="accordion-body">
<strong>This is the second itemβs accordion body.</strong>
</div>
</div>
</div>
<div className="accordion-item" style={light_style}>
<h2 className="accordion-header">
<button
className="accordion-button collapsed" style={light_style}
type="button"
data-bs-toggle="collapse"
data-bs-target="#collapseThree"
aria-expanded="false"
aria-controls="collapseThree"
>
Accordion Item #3
</button>
</h2>
<div
id="collapseThree"
className="accordion-collapse collapse"
data-bs-parent="#accordionExample"
>
<div className="accordion-body">
<strong>This is the third itemβs accordion body.</strong>
</div>
</div>
</div>
<div className="container">
<button
type="button"
onClick={toggle_Btn}
className="btn btn-primary my-2"
>
{btn_text}
</button>
</div>
</div>
</div>
);
}