Open In App

How to Customize the grid layout in React Bootstrap?

Last Updated : 02 Nov, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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:
        category: 'Programming',
    },
    {
        url:
        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:

Ex1

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:

Ex2



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads