Getting class as undefined for img tag in react.js This is the component Header.jsx, Here is the Header.jsx I'm using <img>
, but the CSS properties are not not being implemented in the image, and I'm getting error as 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
This is the css file for the header
/* header.css */
.header__logo{
height: 20px;
width: 50px;
}
In the console I'm getting this error, class="undefined"
<img src="./images/logo.svg" class="undefined" alt="Logo">
Just do like that:Basic Concept
import React from 'react';
import './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="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
When im doing this naming convention I make sure there's a parent tag with the classname you're trying to extend, in this case "header", also helps if your using SCSS with this, 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
Inside your './header.scss'
.header {
// css style for header class
&__logo {
// css style code for logo class
}
}
I find, it returns undefined because it wasn't properly placed in the correct spot within your style sheet. Your react code looks good just missing a few things.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.