Syntax to build a Form Component using React-Bootstrap
<Form>
<Form.Group>
<Form.Label>...<Form.Label>
<Form.Control />
</Form.Group>
</Form>
Example: Conditionally Disabling a Form-input Field. Let’s structure our form component to disable the input text-field name based on the gender.
Javascript
// App.js import React from 'react' ; import FormInputDemo from './FormInputDemo' ; import './App.css' ; const App = () => { return ( <div class= "component" > <FormInputDemo /> </div> ); }; export default App; |
Javascript
// FormInputDemo.jsx import React, { useState } from 'react' ; import { Form, Row, Col } from 'react-bootstrap' ; import './FormInputDemo.css' ; const FormInputDemo = () => { const [gender, setGender] = useState( 'male' ); const handleGenderChange = (event) => { setGender(event.target.value); }; return ( <div> <Form> <Form.Group as={Row}> <Form.Label as= "legend" column sm={2}> Gender </Form.Label> <Col sm={10}> <Form.Check type= "radio" label= "Male" value= "male" checked={gender === 'male' } onChange={handleGenderChange} /> <Form.Check type= "radio" label= "Female" value= "female" checked={gender === 'female' } onChange={handleGenderChange} /> </Col> </Form.Group> <Form.Group controlId= "formName" > <Form.Label>Name</Form.Label> <Form.Control type= "text" placeholder= "Enter name" disabled={gender !== 'female' } className={gender !== 'female' ? 'disabled-input' : '' } /> </Form.Group> </Form> </div> ); }; export default FormInputDemo; |
CSS
/* FormInputDemo */ body { background-color : aliceblue; } .component { display : flex; justify- content : center ; align-items: center ; height : 500px ; } .form-check-label { margin-right : 300px ; } .form-control { border-radius: 4px ; font-size : 16px ; } .form-group { margin-bottom : 20px ; font-weight : bold ; } .container { max-width : 500px ; margin : 0 auto ; padding : 20px ; border : 1px solid #ccc ; border-radius: 8px ; box-shadow: 0 0 10px rgba( 0 , 0 , 0 , 0.1 ); } .disabled-input { cursor : not-allowed; } |
How to Conditionally Disable a Form Input in React-Bootstrap ?
In this article, we will see how to conditionally disable a form input in React-Bootstrap. React-Bootstrap is a popular open-source library for building frontend components with the advantage of the pre-build component features of Bootstrap.