Utilizing the Next.js Image Component in Harmony with MaterialUI

Although I can easily use the <img> tag, I encounter a problem when attempting to utilize the <Image> component. Instead of the image displaying as intended, all that shows is an empty square of the same size. To showcase the image without resorting to the <img> tag, my only successful method thus far has been through the <Avatar> component. While this works for a small brand image, I would prefer to leverage Next.js's built-in image optimization and find a more semantically appropriate solution than using <Avatar>.

The image is contained within a ListItem component structured like so:

<Drawer variant="permanent" {...other}>
            <List disablePadding>
                <ListItem
                    sx={{
                        justifyContent: 'center',
                        alignItems: 'center',
                    }}
                >
                    <Avatar
                        src="images/icons/agreement2.png"
                        alt="Scales of Justice Brand Image"
                        sx={{ width: 50, height: 50 }}
                    />
                </ListItem>

My attempts at resolving this issue include:

  1. Creating a separate component for the image
import Image from 'next/image'
import brandImage from '../public/images/icons/law.png'

export default function Brand() {
    return <Image src={brandImage} width="50px" height="50px" alt="Brand Logo" />
}

and replacing <Avatar> with <Brand /> inside the <ListItem>.

  1. Importing the .png file and using
<Image src={brandImage} width="50px" height="50px" alt="Brand Logo" />

within the <ListItem>. I also attempted to do the same without importing the image, opting instead to use the full file path.

  1. Placing <Image> within the <Avatar> component.
<Avatar>
<Image src={brandImage} width="50px" height="50px" alt="Brand Logo" />
</Avatar>

I experimented with incorporating the layout prop featuring various options.

Currently, I am employing Next.js v12.0.9 and MUI v5.4.2

Answer №1

This solution has been effective for me.

<Container
 sx={{
   height: "500px",
 }}
>
  <Picture
          src={image.data.attributes.url}
          alt={image.data.attributes.alternativeText}
          width={image.data.attributes.width}
          height={image.data.attributes.height}          
          objectFit="cover"
          priority
   />
</Container>

Utilizing Container allows the image to expand to full width seamlessly without needing to specify width as 100%.

Answer №2

If you want to make the image responsive, I suggest creating a container element with a responsive position and adding the image using the following code:

<Box sx={{position:'relative'}}>
<Image src={brandImage} width="50px" height="50px" alt="Brand Logo" />
</Box>

Another way to set it up is like this:

<Box sx={{position:'relative', height:'50px', width:'50px'}}>
    <Image src={brandImage} layout="fill" objectFit="cover" alt="Brand Logo" />
    </Box>

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

Refreshing a sibling component because of data changes in another sibling component within Next JS

I have a Next JS application where I am utilizing the Layout feature within the _app.tsx component. The layout includes a sidebar that is populated from an API call using a GET request. In addition, there is another API call (update request) triggered on ...

Is there a way to refresh my order hook in React JS?

I've been attempting to modify the values within my order hook, but for some reason, they aren't updating. I'm relatively new to React and can't figure out what mistake I might be making. Any insights? Take a look at my code snippet: ...

Exploring the latest upgrades in React 18 with a focus on TypeScript integration

I am currently working on a complex TypeScript project with React and recently made the decision to upgrade to the new version of React 18. After running the following commands: npm install react@18 npm install react-dom@18 npm install @types/react-dom@18 ...

The Material UI Icon rendered using document.createElementNS in React is failing to load properly

I'm currently developing a tags section for my app, similar to the tags feature in a new Stack Overflow question form. For this, I am utilizing the Material UI close icon. You can see how it is implemented in this tutorial on YouTube. (I have confirme ...

iOS app development in React Native 0.64 faces challenges following the update to Xcode 12.5 and iOS 14.5

Having recently upgraded Xcode to version 12.5 and iOS to 14.5, I have encountered issues trying to run my iOS app on both a real device and simulator. Upon executing npm run ios, the following error message is displayed: The following build commands fail ...

The expanding submenus within each menu are activated by a simple click

I am facing an issue with my menus and submenus. Whenever I click on a menu, all the associated submenus also open up. How can I make it so only the parent submenu opens? https://i.stack.imgur.com/7FDq3.png const [subMenu, setSubMenu] = useState(false) ...

What is the process for embedding a NextJS app within a different website?

I'm searching for alternative methods to embed a React/NextJS application within another application. Currently, my solution involves using an iframe and specifying the source as the execution of the React/Nextjs application. I've explored diff ...

Using an array of references within a functional component to dynamically change the class names of individual items using the classList property

As I transition my jQuery-based project to React, I encountered a challenge with using refs in a functional component. In this scenario, I have a large wordlist where each word needs to be accessed via its own ref so that individual classNames can be modif ...

Arrange items evenly within the MUI v5 Grid by using the space grid with justifyContent set to space-evenly

I need help achieving a box with a minimum height of 500px and three cards vertically centered inside it. I have tried using justifyContent="space-evenly" but it doesn't seem to be working as expected. My project is built on MUI v5 ("@ ...

After attempting to sign in with my Google account for the second time, I encountered an OAuthAccountNotLinked error in NextAuth

I'm currently developing a web application using react, nextjs, typescript, mongoose, mongodb, and for authentication, I've integrated next-auth. Before diving into the issue, here are some key points to consider: Users can log in using either ...

When trying to click on an HTMLTableRowElement, an Uncaught ReferenceError occurs in React.js and jQuery, stating that the function is

When I was working on my web app, I encountered an issue while trying to create a table. Upon clicking on it, I received an error message: Uncaught ReferenceError: (function) is not defined at HTMLTableRowElement.onclick Here is the code for the table: $( ...

Encountering an issue with NextJS and mongoose when setting up a login API with bcrypt hashing

I'm in the process of setting up an endpoint that verifies a user's existence and then compares the entered password with the hashed password stored in MongoDB. Utilizing NextJS, Mongoose, and Bcrypt for this task. The user model includes a funct ...

When using the react-query library, the useQuery hook may not always return a defined value, leading

Experimenting with reactQuery in a demo app showcased in this repository. The app interacts with a mock API found here. Encountering an issue using the useQuery hook to call the following function in the product API file: export const getAllProducts = asy ...

Creating a Tailored Import Rule in ESLint for MaterialUI

I'm currently working on a React project that utilizes Material UI, and I've decided to implement one of their recommended strategies to reduce the overall bundle size. The approach involves installing the babel-plugin-transform-imports package ...

Adding array elements to a JavaScript object

I find myself in a rather unique predicament that I'm struggling to navigate. I have come across some data structured as follows. Please bear with me if I use any incorrect terminology, as I am relatively new to this. usersByName: { "tester&q ...

Implementing defaultProps in conjunction with withStyles

Currently, I am in the process of developing a component using material-ui withStylers and defaultProps. However, I have encountered an issue where the props of the component are not being retrieved in the styles objects unless they are explicitly passed t ...

The CSS scale property is not working as expected when used in a React.js application, specifically

working environment ・next.js ・react ・typescript https://www.youtube.com/watch?v=ujlpzTyJp-M A Toolchip was developed based on the referenced video. However, the --scale: 1; property is not being applied. import React, { FunctionComponent ...

Encountering a Netlify 404 error when submitting a form in Gatsby

A common form component is used throughout my website, with the ability to customize the form name as needed. The site itself is constructed using Gatsby and hosted on Netlify. Encountering a frustrating issue where attempting to submit a form results in ...

Issue: Failed to retrieve configuration settings due to the inability to connect with the query-engine-node-api library in Prisma and nextjs framework

In my setup, I am using a fresh project in Next.js with Prisma and a Supabase database on Ubuntu. When running the Prisma push and generate commands in my project, I encounter the same error with both npm and yarn even though I have run all Prisma commands ...

Using Material-UI in a project without the need for create-react-app

My objective is to utilize Material-UI without relying on create-react-app, as I feel that it abstracts too much and hinders my learning process. Unfortunately, all the instructions I have come across are centered around create-react-app. I am aiming to s ...