How to disable a button while loading in React




In this post, we will see how to disable a button while loading something in React.

Assume we have a login page with 2 inputs and a button, the user needs to enter his details. When the user presses the login button we need to validate whether the details
are correct. We need to disable the button during this process so that the user can't click it again.

This is the component we have,

import React from "react";

function App() {

  const [name, setName] = React.useState('');
  const [pass, setPass] = React.useState('');
  const nameChange = e => setName(e.target.value);
  const passChange = e => setPass(e.target.value);

  return (
    <div className="App">
      <input value={name} onChange={nameChange} placeholder="Name"/>
      <input value={name} onChange={nameChange} placeholder="Name"/>
      <button onClick={login}>Login</button>
    </div>
  );
}

export default App;

To disable a button in react, we have an attribute called disabled and we can give it a boolean prop

import React from "react";

function App() {

  const [name, setName] = React.useState('');
  const [pass, setPass] = React.useState('');
  const [load, setLoad] = React.useState(false);
  const nameChange = e => setName(e.target.value);
  const passChange = e => setPass(e.target.value);

  return (
    <div className="App">
      <input value={name} onChange={nameChange} placeholder="Name"/>
      <input value={name} onChange={nameChange} placeholder="Name"/>
      <button disabled={load} onClick={()=> {
		      setLoad(true);
		      login().then(()=> setLoad(false));
	      }}>Login</button>
    </div>
  );
}

export default App;

This will disable the button till the validation gets completed.