Jay Sun
Jay Sun

Reputation: 1601

Insert image into Material-UI AppBar

I've been looking for a way to insert a plain image file into the AppBar of Material-UI on the official docs but it seems like the only non-text things you can put in the AppBar are either text icons or SVG icons. Is there a way to display actual images in the AppBar?

Upvotes: 2

Views: 9115

Answers (2)

Idan
Idan

Reputation: 5450

There are several options to insert a background image for Material-UI AppBar.

Here is one that I prefer:

  1. Import the image:

    import headerBackground from "../../Assets/headerBackground.png";
    
  2. Add the image to the stylesheet as follow:

    header: {
      backgroundImage: `url(${headerBackground})`,
    },
    
  3. Set the class component:

    const classes = useStyles();
    
    return (
     <>
       <AppBar className={classes.header}> ... </AppBar>
    

Here is a complete example:

import React from "react";
import { makeStyles } from "@material-ui/core/styles";
import { AppBar, Toolbar, Typography } from "@material-ui/core";

import headerBackground from "../../Assets/headerBackground.png";
const useStyles = makeStyles((theme) => ({
  header: {
    backgroundImage: `url(${headerBackground})`,
  },
}));

export default function Header(props) {
  const classes = useStyles();

  return (
    <AppBar className={classes.header}>
      <Toolbar>
        <Typography variant="h6">Scroll to Hide App Bar</Typography>
      </Toolbar>
    </AppBar>
  );
}

Upvotes: 3

PavelDD
PavelDD

Reputation: 11

Material-UI has some components in which there are properties that can be assigned to the image. For example CardMedia - the properties of image. But you can also use the standard tag to insert the image.

            <AppBar position="static" color="default" elevation={0} className={classes.appBar}>
                <Toolbar className={classes.toolbar}>
                    <img src="/assets/logo.svg" />
                    <nav>
                        <Link variant="button" color="textPrimary" href="#" className={classes.link}>
                            About
                        </Link>
                    </nav>
                </Toolbar>
            </AppBar>

It works for me.

Upvotes: 1

Related Questions