Tuesday, November 26, 2024
Google search engine
HomeLanguagesHow to Disable a Button in ReactJS ?

How to Disable a Button in ReactJS ?

In this article, we are going to learn about disabling 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.

When a button is disable­d, it becomes unclickable and visually signifie­s 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>

Prerequisites:

Steps to Create React Application:

Step 1: Create a react application by using this command

npx create-react-app disable-button-app

Step 2: After creating your project folder, i.e. disable-button-app, use the following command to navigate to it:

cd  disable-button-app

Project Struture

Approach 1: State Management with Alert Message

The approach involve­s using React’s state hooks to manage button disable­d states. Two functions are create­d for toggling the disabled state, accompanie­d by alerts to provide user massage. The buttons’ appearance­ is determined by conditional internal styling. The internal CSS define­s a centered layout with a promine­nt green heading and distinct style­s for disabled (gray, no cursor) and enabled (re­d, pointer cursor) button states.

Example: In this example, we 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}>Geekforneveropen</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",
    },
};


Step 3: To open the application, use the Terminal and enter the command listed below.

npm start

Output:

How-To-Disable-A-Button-In-ReactJs-Example-1

How To Disable A Button In ReactJs Example 1

Approach 2: Conditional Rendering

Conditional rendering in React involves rendering components based on conditions, enabling or disabling UI elements dynamically. Useful for managing component visibility and interactions.

Example: In this example, we creates a form interface with an input field and a submit button. The button is initially disabled when the input field is empty. Once the user enters text, the button becomes enabled, allowing them to submit. Clicking the button triggers an alert showing the input value.

Javascript




import React, { useState } from 'react';
  
function App() {
    const [inputValue, setInputValue] = useState('');
  
    const handleSubmit = () => {
        if (inputValue.length > 0) {
            alert("Form submitted with value: " + inputValue);
        }
    };
  
    return (
        <div style={styles.container}>
            <h1 style={styles.heading}>Geekforneveropen</h1>
            <input
                type="text"
                value={inputValue}
                onChange={(e) => setInputValue(e.target.value)}
                style={styles.input}
            />
            <button
                onClick={handleSubmit}
                style={inputValue.length === 0
                    ? styles.disabledButton : styles.enabledButton}
                disabled={inputValue.length === 0}
            >
                Submit
            </button>
        </div>
    );
}
  
export default App;
  
const styles = {
    container: {
        textAlign: 'center',
        margin: 'auto',
        padding: '20px',
    },
    heading: {
        fontSize: '34px',
        marginBottom: '10px',
        color: "green",
        borderBottom: "3px solid green",
        paddingBottom: 20,
        borderRadius: "8px",
    },
    input: {
        padding: '10px',
        marginBottom: '10px',
        width: '200px',
        borderRadius: 8,
    },
    disabledButton: {
        backgroundColor: 'gray',
        color: 'white',
        cursor: 'not-allowed',
        margin: 10,
        padding: 15,
        borderRadius: "8px",
        border: "none",
        boxShadow: "0px 0px 10px 0px grey",
    },
    enabledButton: {
        backgroundColor: 'green',
        color: 'white',
        cursor: 'pointer',
        margin: 10,
        padding: 15,
        borderRadius: "8px",
        border: "none",
        boxShadow: "0px 0px 10px 0px grey",
    },
};


To open the application, use the Terminal and enter the command listed below.

npm start

Output:

How-To-Disable-A-Button-In-ReactJs-Example-2

How To Disable A Button In ReactJs Example 2

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

RELATED ARTICLES

Most Popular

Recent Comments