React: “I agree to terms” checkbox example
(27 Articles)
In this article, we’ll create a simple React project with a checkbox and a button:
- If the checkbox is unchecked, the button will be disabled and can not be clicked.
- If the checkbox is checked, the button will be enabled.
Here’s what you’ll see when running the final project:
The Code
Create a new React app and replace the default code in the App.js with the following:
import React, { useState } from 'react';
import './App.css';
const App = () => {
const [agree, setAgree] = useState(false);
const checkboxHandler = () => {
// if agree === true, it will be set to false
// if agree === false, it will be set to true
setAgree(!agree);
// Don't miss the exclamation mark
}
// When the button is clicked
const btnHandler = () => {
alert('The buttion is clickable!');
};
return (
<div className="App">
<div className="container">
<div>
<input type="checkbox" id="agree" onChange={checkboxHandler} />
<label htmlFor="agree"> I agree to <b>terms and conditions</b></label>
</div>
{/* Don't miss the exclamation mark* */}
<button disabled={!agree} className="btn" onClick={btnHandler}>
Continue
</button>
</div>
</div>
);
};
export default App;
And here is the App.css:
* {
margin: 0;
padding: 0;
}
.App {
width: 100%;
height: 100%;
display: flex;
justify-content: center;
align-items: center;
}
.container {
width: 800;
height: 300;
margin: 100px auto;
}
.btn {
margin-top: 20px;
padding: 10px 30px;
cursor: pointer;
}
That’s all. Happy coding ๐
Excellent, it helped me a lot !!
You’re welcome ๐
Nice and concise article. Keep it up man