Is the main content positioned below the sidebar on smaller screens?

In order to achieve a 250px col-2 sidebar with a col-10 main body that collapses into a top navbar and main content beneath it, my goal is set. However, I am facing an issue where the main content body goes underneath the sidebar when the screen size changes. How can I fix this problem? Currently using bootstrap v5.3.0-alpha1 in combination with react.

import React, { useState, useEffect } from "react";

export function Holders() {
    const [isSidebarCollapsed, setIsSidebarCollapsed] = useState(false);

    useEffect(() => {
        const handleResize = () => {
            setIsSidebarCollapsed(window.innerWidth < 1026);
        };

        window.addEventListener('resize', handleResize);
        handleResize();
        return () => window.removeEventListener('resize', handleResize);
    }, []);

    return (
        <div className="container-fluid">
            <div className="row">
                {isSidebarCollapsed ? (
                    <>
                        <nav className="navbar navbar-light bg-light">
                            <span className="navbar-brand mb-0 h1">Collapsed Sidebar</span>
                        </nav>
                        <div className="col-12">
                            main content with top navbar here
                        </div>
                    </>
                ) : (
                    <>
                        <div className="col-md-2" style={{ width: 250, height: '100vh', backgroundColor: 'yellow', overflowY: 'auto' }}>
                            sidebar content here
                        </div>
                        <div className="col-md-10">
                            <h1>Main Content</h1>
                            main content with sidebar here
                        </div>
                    </>
                )}
            </div>
        </div>
    );
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

Answer №1

You are experiencing an issue with the else condition in your code. The problem arises because the parent does not specify if it is using flex. To fix this, you can simply add d-flex to that particular div.

<div className="d-flex">
            <div
              className="col-md-2"
              style={{
                width: 250,
                height: "100vh",
                backgroundColor: "yellow",
                overflow: "hidden",
                overflowY: "auto"
              }}
            >
              sidebar content here
            </div>
            <div className="col-md-10">
              <h1>Main Content</h1>
              main content w sidebar here
            </div>
          </div>

// Get a hook function
const {
  useState, useEffect
} = React;

const App = () => {
  const [isSidebarCollapsed, setIsSidebarCollapsed] = useState(false);

  useEffect(() => {
    const handleResize = () => {
      setIsSidebarCollapsed(window.innerWidth < 1026);
    };

    window.addEventListener("resize", handleResize);
    handleResize();
    return () => window.removeEventListener("resize", handleResize);
  }, []);
  return (
    <div className="container-fluid">
      <div className="row">
        {isSidebarCollapsed ? (
          <div className="p-0 m-0">
            <nav className="navbar navbar-light bg-light">
              <span className="navbar-brand mb-0 h1">Collapsed Sidebar</span>
            </nav>
            <div className="col-12">main content w top navbar here</div>
          </div>
        ) : (
          <div className="d-flex p-0 m-0">
            <div
              className="col-md-2"
              style={{
                width: 250,
                height: "100vh",
                backgroundColor: "yellow",
                overflow: "hidden",
                overflowY: "auto"
              }}
            >
              sidebar content here
            </div>
            <div className="col-md-10">
              <h1>Main Content</h1>
              main content w sidebar here
            </div>
          </div>
        )}
      </div>
    </div>
  );
};

// Render it
ReactDOM.createRoot(
  document.getElementById("root")
).render( <
  App / > ;
);
*{
  padding:0;
  margin:0;
  box-sizing:border-box;
}
<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.2.0/umd/react.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.2.0/umd/react-dom.development.js"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="04666b6b70777076657444312a352a37">[email protected]</a>/dist/css/bootstrap.min.css" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous" />
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="6b0904041f181f190a1b2b5e455a4558">[email protected]</a>/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous"></script>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Utilize Multidimensional Arrays in HTML

I have a pair of fields called url and id. <input type='url' name='data[web][url]'><input type='number' name='data[web][id]'> <input type='url' name='data[web][url]'><input t ...

Guide to Setting the Color of a Link Using CSS

I’ve been attempting to change the color of an ALink using CSS, but it seems like I just can’t get it right. It’s clear that I’m missing something, as I’ve spent quite a bit of time tinkering with this seemingly simple issue and still can’t fi ...

Stop HTML <dialog> from automatically closing using Vue

I'm working on a project where I need to use Vue to programmatically prevent an HTML dialog element from closing when the close event is triggered. Here's the code snippet I am currently using: import {ref} from 'vue'; const dialogTe ...

Are there any drawbacks to converting all instance methods into arrow functions in order to prevent binding loss?

What are the potential drawbacks of converting all instance methods into arrow functions to avoid the "lost binding" issue? For example, when using ReactJS, the statement onClick={this.foo} can lead to lost binding, as it translates to createElement({ ... ...

Utilize Material UI AutoComplete in React to showcase a variety of choices in a list and capture various selections in the form state, including multiple values

I'm looking to implement Autocomplete in a way that it saves a specific property of an object in the form state and displays a different property in the autocomplete options list. For instance, if we have the following option list: [ { gender_name ...

The system has detected an invalid NSStringEncoding value of 0x8000100 while converting NSAttributedString to HTML

I encountered a warning in the debugger while using XCode: It detected an incorrect NSStringEncoding value of 0x8000100 when converting an NSAttributedString to html data. I am unsure of what is causing this issue or how to resolve it. Below is the code sn ...

Placing emphasis on an object that appears following a period of waiting

I'm currently working on enhancing the accessibility of a slider that will be featured on my website. The goal is to create an effect where, after clicking (or pressing enter) on the first slide, the focus shifts to the second slide element, allowing ...

When attempting to organize the layout of the dash app using app.layout=dbc.Container(), an AttributeError occurs, indicating that the 'layout' attribute is not available in the 'tuple' object

I am facing an issue with the script I have: import dash import pandas as pd import numpy as np import database from dash import Dash, dcc, html import dash_bootstrap_components as dbc # create a dash app that is mobile-friendly app = dash.Dash(__name__, ...

Trying to toggle between two Angular components within the app component using a pair of buttons

Currently, I am developing an application that requires two buttons to display different nested apps. Unfortunately, I am unable to use angular routing for this particular design. These two buttons will be placed within the app.component. When Button A i ...

The data retrieved from the API call is outdated

I am struggling with a weather web API that is only showing old data when called in the code. However, when I enter the API URL directly into the browser, it displays the most up-to-date information for the current city. Can anyone help me troubleshoot why ...

What is the correct way to define the onClick event in a React component?

I have been encountering an issue while trying to implement an onClick event in React using tsx. The flexbox and button are being correctly displayed, but I am facing a problem with the onClick event in vscode. I have tried several ideas from the stack com ...

Every individual child component must be assigned a distinct key prop, even if they are pre-defined. - Utilizing REACT

My navigation bar routes are sourced from a JSON file structured like this: { "categorias": [ { "nombre": "Teacher absences", "componentes": [ { "type": "url", ...

In the Bootstrap Grid system, all posts are aligned to the left side

I have created a gallery with Bootstrap in React.js. The posts are currently displayed using the bootstrap grid system, however, all posts appear on the left side and I am struggling to center them. Any ideas on how to achieve this? After applying justify ...

Sharing data between the main component and the sidebar in React-Router

Currently working with Meteor in combination with React-Router, and this is the code I'm dealing with: Routes.jsx: Meteor.startup(() => { render( <Router history={browserHistory}> <Route path='/' component={App}> ...

Create a list of items that are enclosed within a parent element

My menu is generated from a php query and the output is as follows: #ultra-menu { width: 92%; background-color: rgba(255, 255, 255, 0.90); position: absolute; left: 0px; right: 0px; margin: auto; border-radius: 35px; max-height: 300px; ...

Having trouble installing packages on React 18?

Encountering an error while attempting to install a package. Seeking assistance in resolving this issue. npm ERR! code ERESOLVE npm ERR! ERESOLVE could not resolve npm ERR! npm ERR! While resolving: @material-ui/<a href="/cdn-cgi/l/email-protection ...

Incorrect sorting of tables in Bootstrap

I've been struggling to position 3 tables as shown in the image, but they keep stacking vertically instead of horizontally. The desired layout is to have two tables on one side and three on the other side. Can anyone provide guidance on achieving this ...

When hovered over, the Dropdown Menu vanishes into thin air

I'm looking to implement a simple CSS dropdown menu on my website. Here is the code: #topNav { font-size: 12px; width: 970px; margin: 0 auto; height: 33px; background: url(images/menubg.png); /*border-bottom: solid 1px #cccccc;*/ } #topNav ul { margi ...

Discover the benefits of utilizing router.back() cascade in Next/React and how to effectively bypass anchor links

Currently, I am working on developing my own blog website using Next.js and MD transcriptions. The issue I am facing involves anchor links. All the titles <h1> are being converted into anchor links through the use of the next Link component: <Link ...

CSS clearfix doesn't appear to be functioning properly

I've been experimenting with using clearfix instead of the clear both property, but it's not working as expected. Despite following tutorials, the issue persists. How can I troubleshoot this and make it function properly? * { marg ...