How to put an button at the end of the AppBar while still responsive

Viewed 64

I'm Trying to put my login and log out button at the end of the AppBar, if I force with marginLeft: '70%', it goes, but just in the large resolution, others smaller ones the button will stay out of place. This is the forced one

This is the smaller size, it goes to the outside of the AppBar

I've already tried everything in hand but it goes just if forced.

Here goes the Navbar.js

import React, { useState, useEffect, } from 'react'
import { AppBar, Typography, Toolbar, Avatar, Button, Link, Container, Hidden, IconButton, SwipeableDrawer, Divider, List, ListItem,  } from '@material-ui/core';
import { useHistory, useLocation } from 'react-router-dom';
import { useDispatch } from 'react-redux';
import decode from 'jwt-decode';
import * as actionType from '../../constants/actionTypes';
import useStyles from './styles';

import MenuIcon from '@material-ui/icons/Menu';
import PetsOutlinedIcon from '@material-ui/icons/PetsOutlined'
import ChevronRightIcon from '@material-ui/icons/ChevronRight'

export default function Navbar() {
  const [open, setOpen] = useState(false);
  const [user, setUser] = useState(JSON.parse(localStorage.getItem('profile')));
  const dispatch = useDispatch();
  const location = useLocation();
  const history = useHistory();
  const classes = useStyles();

 

  const logout = () => {
    dispatch({ type: actionType.LOGOUT });

    history.push('/auth');

    setUser(null);
  };

  useEffect(() => {
    const token = user?.token;

    if (token) {
      const decodedToken = decode(token);

      if (decodedToken.exp * 1000 < new Date().getTime()) logout();
    }

    setUser(JSON.parse(localStorage.getItem('profile')));
  }, [location]);


  const navigationLinks = [
    { name: 'Animais', href: "#" },
    { name: 'Eventos', href: "#" },
    { name: 'Organizações', href: "#" },
  ];



  return (
    /*Navegação */
    <AppBar className={classes.appBar} color="inherit">
      <Container maxWidth="lg">
        {/**Link pra Home */}


        {/* Altentificação para mostrar usuário online ou pedir para logar*/}
        <Toolbar disableGutters>

          <Link href="/posts" className={classes.pawn}>
            <PetsOutlinedIcon fontSize="large" />
          </Link>


          <Hidden xsDown>
            {navigationLinks.map((item) => (
              <Link className={classes.links}
                variant="button"
                underline="none"
                href={item.href}>
                {item.name}
              </Link>
            ))}

            {/*<Typography className={classes.userName} variant="h6">{user?.result.name}</Typography>*/}

           

            {user?.result ? (
              <div className={classes.logout}>
                <Link href="/posts">
          <Avatar className={classes.avatar} alt={user?.result.name} src={user?.result.imageUrl} href="/posts">
            {user?.result.name.charAt(0)}
            </Avatar></Link>

                <Button variant="contained" color="secondary" onClick={logout}>Sair</Button>
              </div>
            ) : (
              <div className={classes.login}>
                <Button href="/auth" variant="contained" color="primary" >Login</Button>
              </div>
            )}
          </Hidden>
          <Hidden smUp>
            <IconButton className={classes.menu}>
              <MenuIcon onClick={() => setOpen(true)} />
            </IconButton>
          </Hidden>
        </Toolbar>
      </Container>

      {/*Programação para o menu Lateral em mobile*/}
      <SwipeableDrawer className={classes.drawer} anchor="right" open={open}
        onOpen={() => setOpen(true)} onClose={() => setOpen(false)}>
        <div>
          <IconButton>
            <ChevronRightIcon onClick={() => setOpen(false)} />
          </IconButton>
        </div>
        <Divider />
        <List>
          {navigationLinks.map((item) => (
            <ListItem>
              <Link className={classes.links}
                variant="button"
                underline="none"
                href={item.href}>
                {item.name}
              </Link>
            </ListItem>

          ))}
        </List>
        <Divider />


        
        
        {/*<Typography className={classes.userName} variant="h6">{user?.result.name}</Typography>*/}

        {user?.result ? (
          <div className={classes.logout}>
            <Link href="/posts">
          <Avatar className={classes.avatar} alt={user?.result.name} src={user?.result.imageUrl} href="/posts">{user?.result.name.charAt(0)}</Avatar></Link>

            <Button variant="contained" color="secondary" onClick={logout} >Sair</Button>
          </div>
        ) : (
          <div className={classes.login} >
            <Button href="/auth" variant="contained" color="primary" >Login</Button>
          </div>

        )}



      </SwipeableDrawer>
    </AppBar>


  );
};





Here the styles.js of this component without force:

import { makeStyles } from '@material-ui/core/styles';
import { deepPurple } from '@material-ui/core/colors';

export default makeStyles((theme) => ({
  appBar: {
    position: 'sticky',
    marginBottom:  '30px',
    display: 'flex',
    alignItems: 'center',
    padding: '10px 50px',
  },
  userName: {
    display: 'flex',
    alignItems: 'center',
    textAlign: 'center',
  },
  pawn: {
    display: 'flex',
    marginRight: "20px",
    color: theme.palette.secondary.main,
    '&:hover': {
      color:  theme.palette.secondary.dark,
    }
    
  },
  avatar: {
    marginRight: "20px",
    marginLeft: 'auto',
    marginTop:"5px",
    marginBottom:"5px",
    display: 'flex',
    alignItems: 'center',
    
    
  },
  
  links: {
    marginRight: 20,
    color: "#000",
    '&:hover':{
      color:"   #808080"
    }
  },
  list: {
    display: 'flex',
    alignItems: 'center',
    
  },
  logout: {
    display: 'flex',
    alignItems: 'center',
    textAlign: 'center',
    marginLeft: '20px',
  },
  login:{

    display: 'flex',
    alignItems: 'center',
    textAlign: 'center', 
    marginLeft: '20px',
    marginTop: '5px',
  },
  menu: {
    marginRight: "-30px",
    marginLeft: "80%",

  },
  drawer: {
    display: 'flex',
    width: "400px",
  },

  
}));

The Navbar looks like this without force:

This is the xs looks without the force:

the xs looks when forced:

This is my dependencies, in case you need it.


{
  "name": "client",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@emotion/react": "^11.6.0",
    "@emotion/styled": "^11.6.0",
    "@material-ui/core": "^4.9.10",
    "@material-ui/icons": "^4.9.1",
    "@material-ui/lab": "^4.0.0-alpha.58",
    "@testing-library/jest-dom": "^5.15.0",
    "@testing-library/react": "^11.2.7",
    "@testing-library/user-event": "^12.8.3",
    "axios": "^0.19.2",
    "dotenv": "^10.0.0",
    "jwt-decode": "^3.1.2",
    "material-ui-chip-input": "^1.1.0",
    "moment": "^2.27.0",
    "react": "^16.12.0",
    "react-dom": "^16.12.0",
    "react-file-base64": "^1.0.3",
    "react-google-login": "^5.1.25",
    "react-icons": "^4.3.1",
    "react-redux": "^7.1.3",
    "react-router-dom": "^5.2.0",
    "react-scripts": "^3.4.1",
    "redux": "^4.0.5",
    "redux-thunk": "^2.3.0",
    "styled-components": "^5.3.3",
    "web-vitals": "^1.1.2"
  },
  


The MenuIcon at the xs style is forced too, if not it stay right beside the pawn.

I'm doing this based on https://github.com/adrianhajdin/project_mern_memories (I'm using Part6), and it is just for knwoledge purpose, and for my teacher at the code school. Hope I've given all the information so you can understand.

1 Answers

It is normal, if you force it. It doesn't work that way. Try to make the two blocks as two different divs, and then use on the father node the property

justify-content: space-between

You can see it well explained here: https://css-tricks.com/snippets/css/a-guide-to-flexbox/

Have fun with flexbox!

Related