alia
alia

Reputation: 300

Disabled button doesn't work in React JS if text color is specified

I would like to specify style(background and text color) of the button that will be disabled later in code. button needs to look like this on render and like this after click

My code is

import React, { useState, useEffect } from "react";

import "./styles.css";

export default function App() {
  const [loading, setLoading] = useState(false);

  const handleClick = (e) => {
    e.preventDefault();
    setLoading(true);
  };
  return (
    <div className="App">
      <button disabled={loading} onClick={handleClick} className="btn">
        {" "}
        Click me
      </button>
    </div>
  );
}

and Css

.btn {
  width: 200px;
  height: 50px;
  background-color: blue;
  /* color: white; */
}

.btn:hover {
  cursor: pointer;
}

link to codesandbox

When I specify color of the text(white) disabled doesn't change color to grey( button doesn't look disabled), when text color is not defined, it's black and after click it's grey. Is there any way to define text color as white before click, and when button is clicked change color to grey? Because I need to make the button with blue background and white text on render. Thank you anyone who will help me.

Upvotes: 0

Views: 2065

Answers (1)

brianyates
brianyates

Reputation: 399

Most of this can be done with CSS, though you'll need to add one more thing to your React component.

JS:

import React, { useState, useEffect } from "react";

import "./styles.css";

export default function App() {
  const [loading, setLoading] = useState(false);

  const handleClick = (e) => {
    e.preventDefault();
    setLoading(true);
  };
  return (
    <div className="App">
      <button disabled={loading} onClick={handleClick} className={`btn${loading ? ' disabled' : ''}`}>
        {" "}
        Click me
      </button>
    </div>
  );
}

CSS

.btn {
  width: 200px;
  height: 50px;
  background-color: blue;
  /* color: white; */
}
.btn.disabled {
  opacity: .65;
  pointer-events: none;
}
.btn:hover {
  cursor: pointer;
}
.btn:active {
  color: green; // Or whatever style you want
}

EDIT: You can also use the :enabled and :disabled pseudo-selectors like the comment above said.

Upvotes: 1

Related Questions