Tips for securing a navbar in material ui

https://i.stack.imgur.com/CYfmQ.png

In my current React project, I am facing an issue with aligning components within the Material-UI AppBar Component. My aim is to achieve a seamless and perfectly straight alignment for three key elements: a logo image, a heading, and a sign-in button.

Navbar.js Code:


                // Import necessary modules
import { AppBar, Typography, Toolbar, Avatar, Button, Box, Container } from "@mui/material";
import React from "react";
import { Link } from 'react-router-dom';
import useStyles from './styles';
import memories from '../../images/memories.png';

const Navbar = () => {
  const classes = useStyles();
  const user = null;
  return (
      <>
          <AppBar className={classes.appBar} position='static' color='inherit'>
          <Container maxWidth="xl">
          <div className={classes.brandContainer}>
              <img className={classes.image} src={memories} alt="memories" height="50" />
              <Typography variant='h4' nowrap className={classes.heading} >Travel Blog</Typography>
          </div>
          <Toolbar className={classes.toolbar}>
              // Conditional rendering based on user status for profile details or sign-in option
              {user ? (
                  <div className={classes.profile}>
                      <Avatar className={classes.purple} alt={user.result.name} src={user.result.imageUrl}>{user.result.name.charAt(0)}</Avatar>
                      <Typography className={classes.userName} variant='h6'>{user.result.name}</Typography>
                      <Button variant="contained" className={classes.logout} color="secondary">Logout</Button>

                  </div>
              ) : (
                  <Button component={Link} className={classes.login} to='/auth' variant="contained" color="primary">Sign In</Button>
              )}
          </Toolbar>
          </Container>
      </AppBar>
      </>
  )
}

export default Navbar;

                

Styles.js Code:


                // Define styles for the Navbar component using Material-UI makeStyles
import { makeStyles } from "@mui/styles";
import { useTheme } from '@mui/material/styles';
import { deepPurple } from "@mui/material/colors";

// Export custom styles using makeStyles
export default makeStyles(() => ({
  appBar: {
    borderRadius: 15,
    margin: '30px 0',
    display: 'flex',
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    padding: '10px 50px',
  },
  heading: {
    color: 'rgba(0,183,255, 1)',
    textDecoration: 'none',
  },
  image: {
    marginLeft: '15px',
  },
  toolbar: {
    display: 'flex',
    flexDirection: 'row',
    justifyContent: 'flex-end',
    alignItems: 'center'
  },
  profile: {
    display: 'flex',
    justifyContent: 'space-between',
    width: '400px',
    gap: '15px', 
  },
  userName: {
    display: 'flex',
    alignItems: 'center',
  },
  brandContainer: {
    display: 'flex',
    alignItems: 'center',
  },
  purple: {
    color: useTheme().palette.getContrastText(deepPurple[500]),
    backgroundColor: deepPurple[500],
  },
}));
                

Answer №1

Consider incorporating display flex and setting the flex-direction to row within the container element

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

Prevent the hiding of a select element with jQuery Chosen Select

I am facing difficulty hiding a select element with the chosen-select class if it does not have any elements present. I attempted: $("#Category2").hide(); and also tried removing the chosen-select class before hiding the element: $("#Category2").re ...

Is there a way to adjust the border color of my <select> element without disrupting the existing bootstrap CSS styling?

In my Bootstrap (v4.5.3) form, the select options appear differently in Firefox as shown in the image below: https://i.sstatic.net/3suke.png Upon form submission, I have JavaScript code for validation which checks if an option other than "-- Select an Op ...

What could be causing the failure to typecheck the sx prop?

Trying to implement sx prop-based styling in a React project. Looking to utilize the theme using a theme getter. While styles render correctly in the browser, TypeScript raises errors and understanding the type ancestry is proving challenging. Working e ...

Tips for Preventing Page Scrolling When Clicking on a Hashed A Tag in Content with a Fixed

Currently stuck dealing with a challenging problem related to hashed anchor links. Here's a basic representation of the HTML code: <div class="main-wrap"> <header></header> <aside> <nav> <ul> ...

ReactJS: Updating elements in the DOM on the fly

Looking to dynamically change the JSX element tag while keeping other attributes constant. For example, given the following code snippet:- import React, { useState } from 'react' import classNames from 'classnames' import { makeStyles } ...

Whenever my NodeJs encounters an unhandledPromise, it throws an error

exports.createNewTour = async (request, response) => { try { const newlyCreatedTour = await Tour.create(request.body); res.status(201).json({ statusCode: "success", details: { toursData: newlyCreatedTour, }, ...

Pressing the button in JqGrid will assign an identification number

I am facing an issue with selecting rows in my JqGrid, so I found a solution on which suggests that I need an ID for every row. Whenever I add data to my Grid by pressing a button, I tried assigning each row an ID using a simple click counter function. H ...

What is the best way to retrieve past data using RTK Query?

When working with data retrieval using a hook, my approach is as follows: const { data, isLoading } = useGetSomeDataQuery() The retrieved data is an array of items that each have their own unique id. To ensure the most up-to-date information, I implement ...

Issue during Firebase production: emptyChildrenSingleton isn't recognized

In my nextjs project, I am using React v18.1.0 and Firebase Realtime Database for handling notifications. The notifications work fine in development mode but fail in the production environment. The errors I encountered are as follows: ReferenceError: empt ...

What is the process for converting an Angular UTC timestamp to a local timestamp?

Is it possible to convert a UTC timestamp to a local time timestamp using any function or method? I am sending the timestamp to angular moments, but the server's timestamp is in UTC. ...

Taking out the modal element from the document object model, causing the animation

I am currently working on a project using Next.js, Typescript, and Tailwind CSS. Within this project, I have implemented a modal component with some animations. However, I encountered an issue where the modal does not get removed from the DOM when closed, ...

Determine which scroll bar is currently in use

I'm running into an issue with multiple scrollbars on my page - they just don't seem to be functioning correctly: <div class="dates-container" v-for="id in ids"> <overlay-scrollbars :ref="`datesHeader` ...

Prompting Javascript Alert prior to redirection in ASP.NET

My current code is set up to display a message in an update panel while updating: string jv = "alert('Time OutAlert');"; ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "msg", jv, true); It's working well in displaying the me ...

Use jQuery to smoothly scroll a div

I created a container using a <div> element which is divided into 3 inner divs. The first two inner divs are meant to serve as previous and next buttons, with ids of prev and next respectively. At the bottom, there are 3 more inner divs, each with un ...

Ways to refresh the DOM while making an asynchronous request

Consider the following async function: async function predict_from_model() { $("#loading").html("first update") const model = await tf.loadModel('model.json'); $("#loading").html("second update") //delayed for (var i = 0; i < 100; i++ ...

Utilizing CSS to apply unique styles to individual radio buttons

I have 4 radio buttons in my quiz application. I need to style only one of them, which is the correct answer option. Here's the HTML snippet that was generated: <p> <input id="SelectedAnswer" type="radio" value="5" name="SelectedAnswer"> ...

Unable to connect with controller after deploying asp.net mvc ajax call on server

For the first time, I am encountering a new issue. Although my code runs smoothly on my localhost, when I upload it to the server, I get a bad request error. The specific error message is: 400 (Bad Request) Below is the snippet of my code: Controll ...

Utilize Vue.js to transmit HTTP requests with specified headers and parameters

I'm trying to figure out how to create a LinkedIn login component, but I'm having trouble finding information about headers and parameters. Can someone help me understand how to send a GET or POST request with parameters and headers? Here's ...

JavaScript and CSS animations out of sync in terms of timing

I've been encountering some issues. I have an array containing 5 lines of text that change with a timer, but it seems that the css timer animation might not be synced properly or my @keyframes slidesdown setup could be incorrect. The delay between te ...

Dynamic updating of scores using Ajax from user input

My goal is to design a form that includes three "Likert Scale" input fields. Each of these three inputs will have a total of 10 points that can be distributed among them. The submit button should become enabled when the score reaches 0, allowing users to s ...