State Management with Alert Message
The approach involves using React’s state hooks to manage button disabled states. Two functions are created for toggling the disabled state, accompanied by alerts to provide user massage. The buttons’ appearance is determined by conditional internal styling. The internal CSS defines a centered layout with a prominent green heading and distinct styles for disabled (gray, no cursor) and enabled (red, pointer cursor) button states.
Example: This creates a component that displays two buttons, “Disable” and “Enable.” Clicking “Disable” disables the “Disable” button and vice versa. Alert messages confirm the actions.
Javascript
import React, { useState } from 'react' ; function App() { const [isButtonDisabled, setButtonDisabled] = useState( false ); const disableButton = () => { setButtonDisabled( true ); alert( "Button has been disabled!" ); }; const enableButton = () => { setButtonDisabled( false ); alert( "Button has been enabled!" ); }; return ( <div style={styles.container}> <h1 style={styles.heading}>Geekforgeeks</h1> <button onClick={disableButton} style={isButtonDisabled ? styles.disabledButton : styles.enabledButton} disabled={isButtonDisabled} > Disable </button> <button onClick={enableButton} style={!isButtonDisabled ? styles.disabledButton : styles.enabledButton} disabled={!isButtonDisabled} > Enable </button> </div> ); } export default App; const styles = { container: { textAlign: 'center' , margin: 'auto' , padding: '20px' , width: 400, }, heading: { fontSize: '34px' , marginBottom: '10px' , color: "green" , borderBottom: "3px solid green" , paddingBottom: 20, borderRadius: "8px" , }, disabledButton: { backgroundColor: 'gray' , color: 'white' , cursor: 'not-allowed' , margin: 10, padding: 15, borderRadius: "8px" , border: "none" , boxShadow: "0px 0px 10px 0px grey" , }, enabledButton: { backgroundColor: 'red' , color: 'white' , cursor: 'pointer' , margin: 10, padding: 15, borderRadius: "8px" , border: "none" , boxShadow: "0px 0px 10px 0px grey" , }, }; |
Steps to Run the Application: open the application, use the Terminal and enter the command below.
npm start
Output: This output will be visible on the http://localhost:3000/ on the browser window.
How to Disable a Button in React JS ?
Disabling a button in React JS means making it unclickable and visually indicating its unavailability. This is done by setting the button’s disabled attribute to true. It’s used for controlled interactions, like form submissions with valid data.
A disabled button becomes unclickable and visually signifies to the user that its functionality is currently unavailable. This common practice helps prevent users from performing invalid or prohibited actions within a specific context.
Syntax:
<button disabled={true}>Disabled Button</button>