Displaying elements above my React sidebar

I am working on developing a Login application with a landing page using React Router and Redux. In order to have a Sidebar that is always present in all the components within the application, I have setup the Sidebar component as a route that is constantly visible in the URL. Here's how I have implemented it:

index.js

ReactDOM.render(
  <Provider store={store}>
    <Router history={history}>
          <App/>
      </Router>
  </Provider>,
  document.getElementById('root')
);

App.jsx

export default function App() {
    return (
        <Fragment>
            <Route exact path="/login" component={Login} />
            <Route path="/p" component={Sidebar} />
            <PrivateRoute exact path="/p" component={Dashboard} />
        </Fragment>
    );
}

Sidebar.jsx

function Sidebar({ logout }) {
    return (
        <div className="sidebar">
            <Button onClick={logout}>Logout</Button>
        </div>
    )
}

Sidebar.css

.sidebar {
    position: fixed;
    height: 100%;
    width: 75px;
    z-index: 1;
    top: 3.4em;
    background-color: #222;
    overflow-x: hidden;
    padding-top: 10px;
}

Dashboard

export default function Dashboard() {
    return (
        <Fragment>
            Hola
        </Fragment>
    )
}

To ensure the Sidebar sticks to the left of the screen, I have defined styles in Sidebar.css which are functioning correctly. However, the issue arises when adding components like the Dashboard, as it appears at the top of the screen instead of resizing to fit alongside the navbar. See the current layout here: https://i.sstatic.net/kOtYK.png

How can I address this issue and make all subsequent components added to the app adjust their size appropriately for the Navbar to consistently appear on the left side?

Answer №1

The positioning of an element's top edge is affected by the top property.

If you want to eliminate any gap caused by adding 3.4em, simply set it to 0 for no top spacing.

.sidebar {
    ...other properties
    top: 0;
}

Since the positioned element is fixed, it will overlay other user interface elements. To adjust for this in a Dashboard layout, use margin-left: 75px (or the sidebar width).

export default function Dashboard() {
    return (
        <div style={{marginLeft: 75}}>
            Hello
        </div>
    )
}

Answer №2

Get help from Avinash's response to address your CSS styling problem.

Consider using layouts and the children prop for a more efficient approach in implementing the appearance of Sidebar in every component.

To achieve this, create a Layout component and import Sidebar into it. Then, each component requiring the sidebar can simply utilize that layout.

Layout.js

import Sidebar from './Sidebar'

export default function Layout(props) {
    const { children } = props
    return (
        <div>
            <Sidebar />
            {children}
        </div>
    )
}

For example, your Dashboard.js should be structured like this:

import Layout from './Layout'

export default function Dashboard() {
    return (
        <Layout>
            <div style={{marginLeft: 75}}>
                Hola
            </div>
        </Layout>
    )
}

This method eliminates the need for an extra route like:

<Route path="/p" component={Sidebar} />

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

Proper Placement of Required Field Validator Messages

I am having an issue with the validation text appearing behind my textbox instead of below it. Despite setting the display to block in the CSS class for the assignment type and start date, the validation text is not displaying properly. I have tried variou ...

Twice the data fetching through ajax on popup is observed using php mysql

I've been struggling for the past two hours. Attempted : location.reload(); reset form Tried many features, but after closing my popup and reopening it or opening another ID, the previous ID data is still visible. This happens continuously for all ...

Easily convert 100% of the height to pixels

Is there a way in HTML to convert a div's height from 100% to pixels without specifying a particular pixel value? ...

Implement a custom transition delay in DndKit when an item is dropped, utilizing the

When rearranging elements, I notice a slight transition issue where the item briefly returns to its original position before transitioning. I suspect it may be related to the array remapping, but even after optimizing, the problem persists. The transition ...

What steps do I need to take to make sure the Google font I downloaded is functioning properly in my React project

I have encountered an issue with using a Google font in my project... After downloading the font, I included the following CSS code: @font-face { font-family: "Work Sans"; src: local("Work Sans"), url(../src/Fonts/Work_Sans/Wor ...

Adjusting column styles on mobile or desktop devices

My row has two columns <div class="row"> <div class="col-9"> hello </div> <div class="col-3"> world </div> </div> But I want to change the column classes for small screens, so they would be ...

How come inactive links are still able to be clicked on?

I have been experimenting with various methods to disable links, but I seem to be unable to prevent them from being clickable. While I was successful in changing the cursor to 'not-allowed' when hovering over the disabled link, it still remains c ...

SSR with Material UI Drawer encounters issue during webpack production build meltdown

When I attempted to utilize the Material UI SSR example provided by Material-UI (Link), it worked successfully. However, my next step was to integrate the Material-UI Drawer into this example. To do so, I utilized the Persistent drawer example code also pr ...

The Material-UI DataGrid feature allows for the display of column sums, with the sum dynamically updating based on applied filters

I am struggling with calculating the sum of values in the Total Amount column of my Material-UI DataGrid. How can I achieve this and ensure that the sum is also updated when a filter is triggered? Any guidance on how to sum the entire Total Amount column ...

Learn the process of dynamically expanding a specific Bootstrap menu item using jQuery!

To create a left vertical (sidebar) navigation menu, I will be referencing the "Example" located at https://getbootstrap.com/docs/5.0/components/accordion/. Assuming there are three HTML buttons: <button onclick="myFunction1()">Button 1< ...

The compatibility between ReactRouterHashLink and the Material UI drawer is not functioning properly

Currently, I am incorporating the material-ui, react-router, and react-router-hash-link packages into my project. My goal is to implement a material UI drawer alongside an appbar that contains hashlinks which smoothly scroll to specific sections of the p ...

Determining whether a question is finished or unfinished can be based on the page index

Trying to create a progress bar for a form with 11 questions. Each question has an array of objects that flag whether it's complete or incomplete based on user interactions. The aim is for the progress to update when users click 'next' or &a ...

Utilizing a drop-down menu in AngularJS to dynamically change a URL and fetch images

Currently, I am in the process of creating a website using AngularJS that accesses images from reddit and showcases them based on various parameters such as number of votes and date posted. While this is not groundbreaking, my main goal is to enhance my sk ...

I am unfamiliar with this particular operation

I'm currently attempting to integrate MD5 .js from webtoolkit into my project. However, I am facing an issue where the method MD5 is not being recognized when invoked from a script in jQuery. I have already ruled out any problems with loading the js f ...

Experiment with timeout features in jest and react-testing-library for testing functionality

I'm currently practicing Test-Driven Development (TDD) and I have a scenario where a span element should be displayed on the screen after 5 seconds. However, I haven't actually implemented the span yet, so the test is expected to fail. Surprising ...

Unable to connect the CSS file from the JSP during a Cross Domain request in Internet Explorer 9

I have created a GWTP web application and am making AJAX calls to a JSP page on a different domain (Cross domain) from the GWT client side. Most of the time, the CSS files are linking correctly and working fine. However, occasionally they do not link prop ...

I developed a straightforward MVC application that sends an HttpGet request and delivers an array containing 7 randomly generated, unidentified numbers to the View. [RESOLVED

A new MVC app was launched with a simple task of generating 7 random numbers between 0 and 9 to be placed at positions 1 through 7 (without starting with 0). Initially, the numbers are hidden with "X" marks. When the user clicks on the "Submit" button and ...

Having a minor problem in attempting to retrieve a random value

Having trouble generating a random number from a function. Can someone help explain? const MyButton = document.querySelector(".Flipper"); MyButton.addEventListener("click", recordLog); function recordLog (){ MyButton.style.backgr ...

Leverage the power of PHP files within your JavaScript code

I have a PHP file with some calculations that I want to integrate into another JavaScript file. How can I pass variables from JavaScript to perform calculations inside the PHP file? Here is my JavaScript code: $("#upload").on("click", function(){ var ...

What is the best method for removing table rows with a specific class?

I have an html table with several rows, and for some of these rows the class someClass is applied. My question is: How can I delete the rows that have a specific class? <table> <tr class="someClass"> ...</tr> <tr class="someClass"> ...