Toggle Text Selection On and Off
This example showcases a React component that effortlessly switches between two states. It empowers users to enable or disable text selection and alter the background color of a button. By utilizing the useState hook, this component effectively manages these states. With just a simple click of the button, users can seamlessly toggle between a captivating blue and red background while simultaneously controlling the ability to select text on the page.
Example: In this example we are using the above-explained approach.
Javascript
// App.js file import React, { useState } from "react" ; const App = () => { const [allowTextSelection, setAllowTextSelection] = useState( true ); const [isBlueBackground, setIsBlueBackground] = useState( true ); const toggleTextSelection = () => { setAllowTextSelection(!allowTextSelection); }; const handleButtonClick = () => { // Toggle between two colors setIsBlueBackground(!isBlueBackground); // Toggle text selection toggleTextSelection(); }; const bodyStyle = { fontFamily: "Arial, sans-serif" , margin: 0, padding: 0, backgroundColor: "#f5f5f5" , display: "flex" , alignItems: "center" , justifyContent: "center" , height: "100vh" , }; const containerStyle = { maxWidth: "600px" , padding: "20px" , backgroundColor: "#fff" , border: "1px solid #ccc" , borderRadius: "8px" , boxShadow: "0 4px 8px rgba(0, 0, 0, 0.1)" , textAlign: "center" , }; const buttonStyle = { backgroundColor: isBlueBackground ? "#007bff" : "red" , // Toggle between two colors color: "white" , border: "none" , padding: "10px 20px" , borderRadius: "5px" , cursor: "pointer" , fontSize: "16px" , transition: "background-color 0.3s ease" , }; if (!allowTextSelection) { bodyStyle.userSelect = "none" ; } return ( <div style={bodyStyle}> <div style={containerStyle}> <h1>Welcome To w3wiki</h1> <p> A Computer Science portal for geeks. It contains well-written, well-thought, and well-explained computer science and programming articles. </p> <button id= "toggle-button" style={buttonStyle} onClick={handleButtonClick} > Toggle Text Selection </button> </div> </div> ); }; export default App; |
Output:
How to Disable Text Selection in ReactJS ?
In this article, we will see how to disable the text selection in ReactJS.
Contact Us