Author avatar

Gaurav Singhal

How to Use React with React Bootstrap

Gaurav Singhal

  • Jun 22, 2020
  • 10 Min read
  • 6,493 Views
  • Jun 22, 2020
  • 10 Min read
  • 6,493 Views
Web Development
Front End Web Development
Client-side Framework
React

Introduction

React Bootstrap is an open-source UI library built specifically for React to help you use native Bootstrap components as pure React components, such as modals, popovers, buttons, and so on. It's simple to use and can be easily integrated with an existing React app to customizie UI without compromising functionality.

This guide explores how to use React with React Bootstrap in your app.

Setting up a React Bootstrap App

Create a new React project.

1npx create-react-app react-and-react-bootstrap-app
shell

Install react-bootstrap and Bootstrap.

1npm install react-bootstrap bootstrap
shell

Creating a react-bootstrap Modal

Use a react-bootstrap modal that acts as a sign in form popup inside App.js. First, import the useState hook from React to use state variables inside a functional component. Then import both Modal and Button from react-bootstrap along with Bootstrap's minified CSS to use Bootstrap's style classes.

1import React,{useState} from 'react';
2import {Modal} from 'react-bootstrap';
3import {Button} from 'react-bootstrap';
4import 'bootstrap/dist/css/bootstrap.min.css';
jsx

The Modal uses a show prop to control its open state on the page. show stores a boolean value indicating if the popup is supposed to be open or closed. You can toggle show using an event handler hooked to its buttons. Have a look at the following code to render a react-bootstrap modal that opens when you click on the sign-in button.

1...
2function App() {
3  const [show, setShow] = useState(false);
4
5  const handleClose = () => setShow(false);
6  const handleShow = () => setShow(true);
7
8  return (
9    <>
10      <Button variant="primary" onClick={handleShow}>
11        Sign In
12      </Button>
13
14      <Modal show={show} onHide={handleClose}>
15        <Modal.Header closeButton>
16          <Modal.Title>Sign In Form</Modal.Title>
17        </Modal.Header>
18        <Modal.Body>
19         {/*add a react form here*/} 
20         </Modal.Body>
21        <Modal.Footer>
22          <Button variant="secondary" onClick={handleClose}>
23            Sign Up
24          </Button>
25          <Button variant="primary" onClick={handleClose}>
26            Sign In
27          </Button>
28        </Modal.Footer>
29      </Modal>
30    </>
31  );
32}
33
34export default App;
jsx

Creating a Simple Form Inside the Modal

Populate the modal's body with a Form with two input fields: one for entering an email address and the other for a password. Create a state variable to store the email inside the state of the component.

1...
2    const [email,setEmail]=useState('');
3...
jsx

You can use Bootstrap's rows and columns to manage content's layout and enclose the form fields inside the form-group class for a neat view. Attach an onChange handler to the email field that captures the value entered in the field and sets it to the email state variable.

1...  
2<Modal.body>
3 <Form>
4    
5    <div className="form-group">
6
7        <div className="row">
8            <div className="col-3">
9                <label for="email" style={{fontWeight:500}} >Email:</label>                            </div>
10           <div className="col-9">
11               <input name="email" type="text" placeholder="Enter Email..." 
12                        onChange={(e)=>{setEmail(e.target.value)}}                   
13                />
14           </div>  
15        </div>
16              
17  </div>
18  
19  <div className="form-group">
20      <div className="row">
21           <div className="col-3">
22              <label for="password" style={{fontWeight:500}}>Password:</label>
23           </div>
24           <div className="col-9">
25              <input name="password" type="password" placeholder="Enter Password..."/>
26           </div>
27      </div>       
28  </div>
29    
30 </Form>
31</Modal.body>
32...
jsx

To verify whether the state has been set appropriately, log it on the console when the user clicks the sign-in button. You can do this inside modal's handleClose() method, which is fired when the modal closes as shown below.

Adding a react-bootstrap Alert Component

Alerts are a great way to give a sense of feedback to the user upon successful submission of forms or in case of errors. Import the Alert component from react-bootstrap on the top inside App.js.

1import {Alert} from 'react-bootstrap';
jsx

Create a separate functional component for rendering the alert. It returns a react-bootstrap alert containing a heading, content, and a close button. Just like the modal, it uses the show prop to indicate whether the alert will remain opened or closed in the current view.

1function MyAlert() {
2  const [show, setShow] = useState(true);
3
4  return (
5    <>
6      <Alert show={show} variant="success">
7        <Alert.Heading>Welcome user :)</Alert.Heading>
8        <p>
9         you have successfully signed in! 
10        </p>
11        <hr />
12        <div className="d-flex justify-content-end">
13          <Button onClick={() => setShow(false)} variant="outline-success">
14            Close me ya'll!
15          </Button>
16        </div>
17      </Alert>
18
19      {!show && <Button onClick={() => setShow(true)}>Show Alert</Button>}
20    </>
21  );
22}
jsx

Render MyAlert inside App.js .

1...
2      <MyAlert/>
3...
jsx

By default, the alert will remain open on the page due to the initial value of show.

Combining All the Features

For the MyAlert component to interact with the App component, pass in email and another state variable as props to the former. This state variable controls the alert's show state on the page concerning the modal. Since the alert needs to be hidden or closed before the user has clicked to sign in, initialize it as false.

1...
2    const [showAlert,setShowAlert]=useState(false);
3...
jsx

Set it to true when the user clicks to sign in inside handleClose() of the modal.

1...
2    const handleClose = () =>{
3    console.log(email);
4     setShow(false);
5     setShowAlert(true);
6  }
7...
jsx

Conditionally render the MyAlert component and pass in email and showAlert as props.

1...
2    {showAlert && < MyAlert email={email} showAlert={showAlert} />} 
3...
jsx

Initialize show as showAlert inside the MyAlert component so the alert is initially closed and is fired only when the user clicks the sign-in button.

1...
2    const [show, setShow] = useState(showAlert);
3...
jsx

Output email inside the alert's body.

1...
2    <p>
3          {email} has successfully signed in!
4    </p>
5...
jsx

Finally, your App.js will look like this:

1import React,{useState} from 'react';
2import {Modal, Form} from 'react-bootstrap';
3import {Button} from 'react-bootstrap';
4import {Alert} from 'react-bootstrap';
5import 'bootstrap/dist/css/bootstrap.min.css';
6
7
8
9function MyAlert({email,showAlert}) {
10  const [show, setShow] = useState(showAlert);
11
12  return (
13    <>
14      <Alert show={show} variant="success">
15        <Alert.Heading>Welcome user :)</Alert.Heading>
16        <p>
17          {email} has successfully signed in!
18        </p>
19        <hr />
20        <div className="d-flex justify-content-end">
21          <Button onClick={() => setShow(false)} variant="outline-success">
22            Exit
23          </Button>
24        </div>
25      </Alert>
26
27      
28    </>
29  );
30}
31
32function App() {
33  const [show, setShow] = useState(false);
34  const [email,setEmail]=useState('');
35  const [showAlert,setShowAlert]=useState(false);
36  const handleClose = () =>{
37    console.log(email);
38     setShow(false);
39     setShowAlert(true);
40  }
41  const handleShow = () => setShow(true);
42
43  return (
44    <>
45      <Button variant="primary" onClick={handleShow}>
46        Sign In
47      </Button>
48
49      <Modal show={show} onHide={handleClose}>
50        <Modal.Header closeButton>
51          <Modal.Title>Sign In Form</Modal.Title>
52        </Modal.Header>
53        <Modal.Body>
54          <Form>
55            <div className="form-group">
56
57              <div className="row">
58                <div className="col-3">
59                  <label for="email" style={{fontWeight:500}} >Email:</label>
60                </div>
61                <div className="col-9">
62                  <input name="email" type="text" placeholder="Enter Email..." onChange=                    {(e)=>{setEmail(e.target.value)}                   
63                    }/>
64                </div>  
65              </div>
66              
67            </div>
68            <div className="form-group">
69              <div className="row">
70              <div className="col-3">
71                <label for="password" style={{fontWeight:500}}>Password:</label>
72              </div>
73              <div className="col-9">
74                <input name="password" type="password" placeholder="Enter Password..."/>
75
76              </div>
77              </div>
78              
79            </div>
80          </Form>  
81        </Modal.Body>
82        <Modal.Footer>
83          <Button variant="secondary" onClick={handleClose}>
84            Sign Up 
85          </Button>
86          <Button variant="primary" onClick={
87            handleClose
88            
89          }>
90           Sign In Now
91          </Button>
92        </Modal.Footer>
93      </Modal>
94
95     {showAlert && < MyAlert email={email} showAlert={showAlert} />} 
96    </>
97  );
98}
99
100export default App;
jsx

Now you have a modal that opens a sign-in form connected to your state, which triggers an alert when a user clicks the sign-in button.

Conclusion

In this guide you learned how to use regular React features, such as managing the state, conditionally rendering a component, and passing props to a child component, with React Bootstrap components. React Bootstrap is a great library that provides several other functionalities. You can conveniently mold the utility of any React Bootstrap component to align with your existing app's features.

I hope this guide helped you get started with React Bootstrap. I would also recommend going through the documentation to learn more about available components.