Encountering the issue of receiving an undefined class when using the img tag in a

In my React.js project, I encountered an issue where the class for the img tag is appearing as undefined. The problem lies within the Header.jsx component. In this file, I am using the <img> tag but the CSS properties are not being applied to the image. As a result, I am seeing an error stating class=undefined.

import React from 'react';
import classes from './header.css';
import { Box, Grid, Typography } from '@mui/material';

const Header = () => {
  return (
    <>
      <Box sx={{ flexGrow: 1 }}>
        <Grid container spacing={3}>
          <Grid item xs>
            <img src='./images/logo.svg' className={`${classes.header__logo}`} alt='Logo'/>
          </Grid>
          <Grid item xs={6}>
              <Typography>gbr</Typography>
          </Grid>
          <Grid item xs>
              <Typography>gbr</Typography>
          </Grid>
        </Grid>
      </Box>
    </>
  )
}

export default Header

The following snippet shows the CSS file used for styling the header:

/* header.css */

.header__logo{
    height: 20px;
    width: 50px;
}
    

Upon checking the console, the error message class="undefined" is displayed.

<img src="./images/logo.svg" class="undefined" alt="Logo">

Answer №1

Follow these steps: Understanding the Basics

import React from 'react';
import './header.css';
import { Box, Grid, Typography} from '@mui/material';

const HeaderComponent = () => {
  return (
    <>
      <Box sx={{ flexGrow: 1 }}>
        <Grid container spacing={3}>
          <Grid item xs>
            <img src='./images/logo.svg' className="header__logo" alt='Logo'/>
          </Grid>
          <Grid item xs={6}>
              <Typography>gbr</Typography>
          </Grid>
          <Grid item xs>
              <Typography>gbr</Typography>
          </Grid>
        </Grid>
      </Box>
    </>
  )
}

export default HeaderComponent

Answer №2

When I follow this naming convention, I always ensure there is a parent tag with the specified classname to extend, in this scenario it's "header". It also works well when using SCSS, you can try something like this:

import React from 'react';
import classes from './header.scss';
import { Box,Grid, Typography} from '@mui/material';

const Header = () => {
  return (
    <div className={`${classes.header}`>
      <Box sx={{ flexGrow: 1 }}>
        <Grid container spacing={3}>
          <Grid item xs>
            <img src='./images/logo.svg' className={`${classes.header__logo}`} alt='Logo'/>
          </Grid>
          <Grid item xs={6}>
              <Typography>gbr</Typography>
          </Grid>
          <Grid item xs>
              <Typography>gbr</Typography>
          </Grid>
        </Grid>
      </Box>
    </>
  )
}

export default Header

In your './header.scss' file:

.header {
  // CSS styles for the header class

  &__logo {
    // CSS style code for the logo class
  }
}

The issue of returning undefined may be due to its incorrect placement within your stylesheet. Your react code appears fine but just needs a few adjustments.

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

Creating unique CSS div designs based on the nth-child selector

I have created a website layout. https://i.stack.imgur.com/6FSEb.png I have included the file showing the design. The data in the boxes will come from a MySQL database. My query is, can it be done with just one query? Currently, I am running separate q ...

How to obtain the first and last elements of an array using ES6 syntax

let array = [1,2,3,4,5,6,7,8,9,0] This is an example of how documentation might look [first, ...rest] = array will give you 1 and the rest of the array My question now is whether it is possible to only extract the first and last elements 1 & 0 using ...

How can you get the selected option from a drop-down menu using JavaScript without using JQuery?

UPDATE: JSFiddle Link I'm facing some challenges with this task. I'm trying to keep my code clean without overusing unnecessary IDs or classes. The issue lies with a drop-down menu that offers speed options for displaying words in real-time on ...

Create a ReactJs hierarchical tree component that illustrates the relationship between employees and managers

I need to create a ReactJs Tree component using Material UI that displays managers and their employees. When a manager is clicked, the component should expand to show all employees reporting to them. How can I achieve this with the provided data structure? ...

Managing file system operations in Node.js

What is the most effective way to manage file access in node.js? I am currently developing an http-based uploader for exceptionally large files (10sGB) that allows for seamless resumption of uploads. I am trying to determine the optimal strategy for handl ...

Verifying if checkboxes are selected in PHP using JavaScript

echo '<div class="col-lg-10 col-lg-offset-1 panel">' . "<table id='data' class='table'> <tr> <th></th> <th>Document No</th> <th>AWB NO</th> ...

Achieve full parent width with floated divs

My goal is to arrange 10 boxes horizontally on a webpage. Each box must have a minimum width of 150px and a maximum width of 299px. The challenge is to fit as many boxes as possible across the page without any gaps, ensuring that each box has an equal widt ...

Having trouble retrieving returned data after refetching queries using Apollo and GraphQL

I am able to track my refetch collecting data in the network tab, but I am facing difficulty in retrieving and using that data. In the code snippet below where I am handling the refetch, I am expecting the data to be included in {(mutation, result, ...res ...

"Exploring the methods to retrieve Firebase authentication error details and outputting the console log message along with

When I encounter an error in Firebase authentication, I want to display it in the console log. However, nothing is being logged and the catch block is not even getting executed. I am unsure about why this is happening and how to retrieve the error code and ...

Is there a way to display a delivery estimate underneath the product title on a WooCommerce website?

How can I display Estimated delivery days below the product title to inform my customers about their order's arrival date, similar to the example on the page included in the link? I would like it to show varying days depending on the shipping class. ...

The main menu vanishes when you hover over it after the affix class is activated

I am currently working on creating a horizontal dropdown menu that expands on mouseover and collapses on mouseout under one of the main menu items. The functionality of this effect is working fine, except for one issue. When I scroll down and activate the ...

An array becomes undefined once the previous array is removed

Consider the following code snippet: using the splice method, a specific item from Array1 is retrieved and stored in a variable called Popped. Next, Popped is added to array2. However, if we then delete the value from Popped, why does array2 become undef ...

Firefox is not rendering HTML5 elements properly

While my website performs well in Chrome and Safari, there seems to be an issue with how elements are displayed in Firefox or IE. Some elements are being pushed to the right, and I am unsure of how to fix this problem. You can view the site here To aid i ...

Prevent the Button from causing the Aspx Page to refresh

I've been working on a JavaScript function for my website that displays a popup when a button is clicked. However, every time I click the button, the webpage reloads causing the popup to disappear. Is there a way to prevent the page from refreshing wh ...

Experiencing an excessive number of redirections on the AWS API gateway due to the frontend application

In our current setup, we have a React application running in Kubernetes (k8s) and exposed through an Istio Virtual Service. Since we are operating within a VPN, all our application endpoints use HTTP by default. However, there was a specific requirement to ...

Is it possible to create a sticky element that stays fixed to the window without using JavaScript?

Using position: sticky has been a game-changer for me. It resolves many issues without the need for JavaScript. However, I've encountered a roadblock. I am trying to create a sticky element that is nested inside multiple <div> elements. Since po ...

Propositional Properties within the Interface

I have a question about interfaces: Currently, I am working on a dynamic component that needs to change based on the page it's on. The structure of my interface is as follows: interface Props { heading: string; description: string; signUp?: boolean; ...

Having trouble sending an array from Flask to a JavaScript function

As a newcomer to web development and JavaScript, I'm struggling to pass an array from a Flask function into a JavaScript function. Here's what my JS function looks like: function up(deptcity) { console.log('hi'); $.aja ...

AngularJS using the ng-controller directive

I am presenting the following HTML code excerpt... <!DOCTYPE html> <html lang="en-US" ng-app> <head> <title>priklad00007</title> <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angula ...

Tips for preventing the first character of a word in the input box from being "-"

I'm looking for a solution to prevent the first character in a text box from being a "-" symbol. $(document).on("keypress", "#form_name", function() { if ($('#form_name').val().substr(0, 1) == "-") { return true } else { return ...