How to Customize the grid layout in React Bootstrap?
Last Updated :
02 Aug, 2024
In this article, we will be customizing the grid layout in React Bootstrap. Grid layout is used to align the elements with ting the grid format according to the requirements. In React Bootstrap, we can control the number of columns, spacing, responsiveness, and other properties to create a more attractive User Interface.
Prerequisites
Steps to Create React Application and Installing Bootstrap:
Step 1: Create a React application using the following command:
npx create-react-app grid-custom
Step 2: After creating your project folder(i.e.grid-custom), move to it by using the following command:
cd grid-custom
Step 3: Now install react-bootstrap in your working directory i.e. grid-custom by executing the below command in the VScode terminal:
npm install react-bootstrap
Step 4: Now we need to Add Bootstrap CSS to the index.js file:
import 'bootstrap/dist/css/bootstrap.min.css';
Project Structure

The updated dependecies in package.json will look like :
"dependencies": {
"react": "^18.2.0",
"react-bootstrap": "^2.9.1",
"react-scripts": "5.0.1",
"web-vitals": "^2.1.4"
}
Example 1: This example creates a basic Photo Gallery using Grid Structure of React Bootstrap
JavaScript
import React, { useState } from 'react';
import {
Container, Row, Col, Modal,
Button, Dropdown, Form
} from 'react-bootstrap';
const images = [
{
url:
'https://media.geeksforgeeks.org/img-practice/banner/dsa-interview-preparation-classroom-thumbnail.png?v=19658',
category: 'Programming',
},
{
url:
'https://media.geeksforgeeks.org/img-practice/banner/complete-java-backend-development-program-thumbnail.png?v=19658,
category: 'Programming',
},
{
url:
'https://media.geeksforgeeks.org/img-practice/banner/complete-data-analytics-program-thumbnail.png?v=19658',
category: 'Data Analytics',
},
{
url:
'https://media.geeksforgeeks.org/img-practice/banner/mern-full-stack-development-classroom-thumbnail.png?v=19660',
category: 'Web Development',
},
];
const itemsPerPage = 8;
const App = () => {
const [showModal, setShowModal] =
useState(false);
const [selectedImage, setSelectedImage] =
useState('');
const [currentPage, setCurrentPage] =
useState(1);
const [selectedCategory, setSelectedCategory] =
useState('All');
const [gridDirection, setGridDirection] =
useState('horizontal');
const [imageMargin, setImageMargin] =
useState('20px');
const openModal = (image) => {
setSelectedImage(image);
setShowModal(true);
};
const handlePageChange = (page) => {
setCurrentPage(page);
};
const toggleGridDirection = () => {
setGridDirection(gridDirection ===
'horizontal' ?
'vertical' : 'horizontal');
};
const filterImages = () => {
return selectedCategory === 'All'
? images
: images.filter(
(image) =>
image.category === selectedCategory);
};
const paginatedImages = filterImages().slice(
(currentPage - 1) * itemsPerPage,
currentPage * itemsPerPage
);
const gridLayout = {
display: 'grid',
gridTemplateColumns: gridDirection ===
'horizontal' ?
'repeat(auto-fit, minmax(200px, 1fr))' : '1fr',
gap: imageMargin,
};
return (
<Container fluid>
<Row>
<Col xs={12}>
<h1 className="text-success"
style={{ marginTop: '50px' }}>
GeeksforGeeks
</h1>
<h3>Grid Customization - 1</h3>
</Col>
</Row>
<Row>
<Col xs={12} md={6}>
<Dropdown>
<Dropdown.Toggle variant="secondary" block>
Filter by Category: {selectedCategory}
</Dropdown.Toggle>
<Dropdown.Menu>
<Dropdown.Item onClick={() =>
setSelectedCategory('All')}>
All
</Dropdown.Item>
<Dropdown.Item onClick={() =>
setSelectedCategory('Programming')}>
Programming
</Dropdown.Item>
<Dropdown.Item onClick={() =>
setSelectedCategory('Data Analytics')}>
Data Analytics
</Dropdown.Item>
<Dropdown.Item
onClick={() =>
setSelectedCategory('Web Development')}>
Web Development
</Dropdown.Item>
</Dropdown.Menu>
</Dropdown>
</Col>
<Col xs={12} md={6}>
<Button variant="secondary"
onClick={toggleGridDirection} block>
Toggle Grid Direction
</Button>
</Col>
</Row>
<Row>
<Col xs={12} md={4}>
<Form>
<Form.Group>
<Form.Label>Image Margin</Form.Label>
<Form.Control
type="text"
value={imageMargin}
onChange={(e) =>
setImageMargin(e.target.value)}
/>
</Form.Group>
</Form>
</Col>
</Row>
<Row>
<Col xs={12} style={gridLayout}>
{
paginatedImages.map((image, index) => (
<div key={index} className="mb-4">
<div className="photo"
onClick={() => openModal(image.url)}>
<img src={image.url}
alt={`Photo ${index + 1}`}
className="img-fluid" />
<div className="overlay">
<p className="text-white">
Photo {index + 1}
</p>
</div>
</div>
</div>
))}
</Col>
</Row>
<Row>
<Col xs={12}
className="pagination justify-content-center">
{
Array
.from(
{
length: Math
.ceil(filterImages().length / itemsPerPage)
}).map((_, index) => (
<Button
key={index}
variant=
{currentPage ===
index + 1 ?
'success' : 'secondary'}
onClick={() =>
handlePageChange(index + 1)}
>
{index + 1}
</Button>
))}
</Col>
</Row>
<Modal show={showModal}
onHide={() =>
setShowModal(false)} centered>
<Modal.Body>
<img src={selectedImage}
alt="Selected"
className="img-fluid" />
</Modal.Body>
</Modal>
</Container>
);
};
export default App;
Steps to run the application:
Step 1: Run the application using the following command from the root directory of the project:
npm start
Step 2: Now open your browser and go to http://localhost:3000/, you will see the following output
Output:
Example 2: This example creates a customized grid layout using React Bootstrap by providing users with interactive controls to adjust the grid's appearance.
JavaScript
import React, { useState } from 'react';
import {
Container, Row, Col,
ButtonGroup, Button, Form
} from 'react-bootstrap';
const App = () => {
const [numCols, setNumCols] = useState(4);
const [bgColor, setBgColor] = useState('#007bff');
const [borderColor, setBorderColor] = useState('#333');
const [textColor, setTextColor] = useState('#fff');
const handleColChange = (event) => {
setNumCols(parseInt(event.target.value, 10));
};
const handleColorChange = (event, stateSetter) => {
stateSetter(event.target.value);
};
const gridItems =
Array.from(
{ length: numCols * 3 },
(_, index) => index + 1);
const gridCellStyle = {
backgroundColor: bgColor,
border: `2px solid ${borderColor}`,
padding: '20px',
textAlign: 'center',
borderRadius: '5px',
color: textColor,
transition: 'background-color 0.3s, color 0.3s',
};
const handleGridItemHover = (event) => {
event.currentTarget
.style.backgroundColor = '#ff7f50';
};
const handleGridItemLeave = (event) => {
event.currentTarget
.style.backgroundColor = bgColor;
};
return (
<div>
<header style={
{
background: '#fff', padding: '10px',
color: 'green', textAlign: 'center'
}}>
<h1>GeeksforGeeks</h1>
</header>
<h3>
<center>
Grid Layout - 2
</center>
</h3>
<Container>
<Form>
<Form.Group controlId="numCols">
<Form.Label>
Number of Columns
</Form.Label>
<Form.Control type="number"
value={numCols}
onChange={handleColChange} />
</Form.Group>
<Form.Group controlId="bgColor">
<Form.Label>
Background Color
</Form.Label>
<Form.Control type="color"
value={bgColor}
onChange={(e) =>
handleColorChange(e, setBgColor)} />
</Form.Group>
<Form.Group controlId="borderColor">
<Form.Label>
Border Color
</Form.Label>
<Form.Control type="color"
value={borderColor}
onChange={(e) =>
handleColorChange(e, setBorderColor)} />
</Form.Group>
<Form.Group controlId="textColor">
<Form.Label>Text Color</Form.Label>
<Form.Control type="color"
value={textColor}
onChange={(e) =>
handleColorChange(e, setTextColor)} />
</Form.Group>
</Form>
<ButtonGroup>
{[1, 2, 3, 4].map((cols) => (
<Button
key={cols}
variant="primary"
onClick={() => setNumCols(cols)}
active={numCols === cols}>
{cols} Columns
</Button>
))}
</ButtonGroup>
<Row>
{gridItems.map((item) => (
<Col key={item}
xs={12}
md={12 / numCols}>
<div
className="custom-grid-item"
style={gridCellStyle}
onMouseEnter={handleGridItemHover}
onMouseLeave={handleGridItemLeave}>
<h3>
GeeksforGeeks Article {item}
</h3>
</div>
</Col>
))}
</Row>
</Container>
</div>
);
};
export default App;
Output:
Similar Reads
Non-linear Components
In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
JavaScript Tutorial
JavaScript is a programming language used to create dynamic content for websites. It is a lightweight, cross-platform, and single-threaded programming language. JavaScript is an interpreted language that executes code line by line, providing more flexibility.JavaScript on Client Side : On client sid
11 min read
Web Development
Web development is the process of creating, building, and maintaining websites and web applications. It involves everything from web design to programming and database management. Web development is generally divided into three core areas: Frontend Development, Backend Development, and Full Stack De
5 min read
Class Diagram | Unified Modeling Language (UML)
A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read
Spring Boot Tutorial
Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
React Interview Questions and Answers
React is an efficient, flexible, and open-source JavaScript library that allows developers to create simple, fast, and scalable web applications. Jordan Walke, a software engineer who was working for Facebook, created React. Developers with a JavaScript background can easily develop web applications
15+ min read
HTML Tutorial
HTML stands for HyperText Markup Language. It is the standard language used to create and structure content on the web. It tells the web browser how to display text, links, images, and other forms of multimedia on a webpage. HTML sets up the basic structure of a website, and then CSS and JavaScript
10 min read
JavaScript Interview Questions and Answers
JavaScript (JS) is the most popular lightweight, scripting, and interpreted programming language. JavaScript is well-known as a scripting language for web pages, mobile apps, web servers, and many other platforms. Both front-end and back-end developers need to have a strong command of JavaScript, as
15+ min read
Backpropagation in Neural Network
Backpropagation is also known as "Backward Propagation of Errors" and it is a method used to train neural network . Its goal is to reduce the difference between the modelâs predicted output and the actual output by adjusting the weights and biases in the network. In this article we will explore what
10 min read
Polymorphism in Java
Polymorphism in Java is one of the core concepts in object-oriented programming (OOP) that allows objects to behave differently based on their specific class type. The word polymorphism means having many forms, and it comes from the Greek words poly (many) and morph (forms), this means one entity ca
7 min read