<html>
<head>
<meta charset="UTF-8" />
<script src="https://unpkg.com/react@17.0.2/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@17.0.2/umd/react-dom.development.js"></script>
<script src="https://unpkg.com/@babel/standalone@7.14.7/babel.min.js"></script>
</head>
<body>
<div id="app"></div>
<script type="text/babel">
const { useState, useEffect } = React;
function App() {
const [firstName, setFirstName] = useState("");
const [lastName, setLastName] = useState("");
const [isButtonDisabled, setIsButtonDisabled] = useState(true);
useEffect(() => {
setIsButtonDisabled(firstName.length < 3 || lastName.length < 3);
}, [firstName, lastName]);
const addNewCustomer = async (name, surname) => {
//handle submit function as you want
await service.addCustomer(name, surname);
props.funcParam();
};
return (
<div className="container">
<h3>React Js disable button according to input length</h3>
<form>
<input
className="input-field"
type="text"
placeholder="First Name"
value={firstName}
onChange={(e) => setFirstName(e.target.value)}
/>
<input
className="input-field"
type="text"
placeholder="Last Name"
value={lastName}
onChange={(e) => setLastName(e.target.value)}
/>
<button
className="add-button"
disabled={isButtonDisabled}
onClick={() => addNewCustomer(firstName, lastName)}
>
Add
</button>
</form>
</div>
);
}
ReactDOM.render(<App />, document.getElementById("app"));
</script>
<style>
.container {
max-width: 500px;
margin: 0 auto;
padding: 20px;
border-radius: 8px;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}
.input-field {
width: 200px;
height: 30px;
margin-bottom: 10px;
padding: 5px;
border: 1px solid #ccc;
border-radius: 4px;
}
.add-button {
width: 100px;
height: 30px;
background-color: #4caf50;
color: white;
border: none;
border-radius: 4px;
cursor: pointer;
}
.add-button:disabled {
background-color: #ccc;
cursor: not-allowed;
}
</style>
</body>
</html>