So I am making a react app, and I think it's better to show you the code than explain:
Body.js:
import React from 'react';
import Clearsky from "Images/clearsky.jpg";
import Rain from "Images/clearsky.jpg";
import Cloudy from "Images/clearsky.jpg";
const type = {
CLEARSKY: "clearsky",
RAIN: "rain",
CLOUDY: "cloudy"
}
class LeftSide extends React.Component {
constructor(props) {
super(props);
this.state = {
type: this.props.type,
degrees: this.props.degrees
}
}
render() {
return (
""
);
}
}
export default function Body() {
//This is printing the correct path and if I type it in the browser I can see the image.
console.log(type.CLEARSKY);
const style = {
//Not working
backgroundImage: `url(${Clearsky})`
}
return (
<div className="body" style={style}>
<LeftSide />
</div>
);
}
Header.js (uses material-ui.com):
import React from 'react';
import { makeStyles } from '#material-ui/core/styles';
import AppBar from '#material-ui/core/AppBar';
import Toolbar from '#material-ui/core/Toolbar';
import Typography from '#material-ui/core/Typography';
import IconButton from '#material-ui/core/IconButton';
import MenuIcon from '#material-ui/icons/Menu';
import logo from "Images/icon.png";
const useStyles = makeStyles((theme) => ({
root: {
flexGrow: 1,
},
menuButton: {
marginRight: theme.spacing(2),
},
title: {
flexGrow: 1,
},
}));
export default function Header() {
const classes = useStyles();
return (
<div className={classes.root}>
<AppBar position="fixed" style={{ borderRadius: "25px"}}>
<Toolbar>
<IconButton edge="start" className={classes.menuButton} color="inherit" aria-label="menu">
<MenuIcon />
</IconButton>
<Typography variant="h6" className={classes.title}>
Weather
</Typography>
<img src={logo} alt="Icon" height="50" width="50" />
</Toolbar>
</AppBar>
</div>
);
}
index.js:
import React from "react";
import ReactDOM from "react-dom";
import Header from "./Header.js";
import Body from "./Body.js";
export default function App() {
return (
<div className="App">
<Header />
<Body />
</div>
);
}
ReactDOM.render(<App />, document.getElementById("root"));
However the backgroundImage on Body.js is not working, just the default white background.
Tried:
Image from an online server (not a local image).
Setting backgroundSize.
EDIT:
My directory:
src:
Images:
EDIT 2:
I have noticed that if I change the LeftSide component to return
<p>A</p>
Instead of "" it will render this in the browser:
Part of the image has been rendered.
Now I believe it is something with the css.
Solved by adding the following css:
const style = {
//Now working
backgroundImage: `url(${Clearsky})`,
height: "100vh",
backgroundSize: "cover",
}
The issue was the height and the size.
I believe your code is correct, but the div with the background has no width and height enough to be visible. Please check if this is the case.
Working sample (see lines 31 and 32): https://codesandbox.io/s/holy-pine-wpdw7
Related
I am trying to write out a website with responsive-based app bar with a drawer tagged onto it. I am using this design found at https://medium.com/#tsubasakondo_36683/create-responsive-drawer-menu-with-react-material-ui-617a42764b69 and modifying it accordingly. But unfortunately, I am getting this issue, in which the drawer covers the portion of the content trying to be displayed. Please know that I have seen similar questions on this site, but I couldn't figure out how to solve them or the answers were kind of vague. Any help would be much appreciated, please let me know if I need to clarify anything further. All of this is using Material UI components.
Here is my code:
Material UI App-Bar
//Used code: https://medium.com/#tsubasakondo_36683/create-responsive-drawer-menu-with-react-material-ui-617a42764b69
//Picture/Icon Imports
import home from "../Icons/home.png";
import about from "../Icons/about.png";
import contact from "../Icons/contact.png";
import resume from "../Icons/resume.png";
import minecraft from "../Icons/minecraft.png";
import github from "../Icons/github.png"
import React from 'react';
import PropTypes from 'prop-types';
import AppBar from '#material-ui/core/AppBar';
import CssBaseline from '#material-ui/core/CssBaseline';
import Drawer from '#material-ui/core/Drawer';
import Hidden from '#material-ui/core/Hidden';
import IconButton from '#material-ui/core/IconButton';
import List from '#material-ui/core/List';
import ListItem from '#material-ui/core/ListItem';
import ListItemText from '#material-ui/core/ListItemText';
import MenuIcon from '#material-ui/icons/Menu';
import CloseIcon from '#material-ui/icons/Close';
import Toolbar from '#material-ui/core/Toolbar';
import Typography from '#material-ui/core/Typography';
import { makeStyles, useTheme } from '#material-ui/core/styles';
import {Link} from "react-router-dom";
const drawerWidth = 240;
const useStyles = makeStyles(theme => ({
root: {
display: 'flex',
},
drawer: {
[theme.breakpoints.up('sm')]: {
width: drawerWidth,
flexShrink: 0,
},
},
appBar: {
zIndex: theme.zIndex.drawer + 1,
},
menuButton: {
marginRight: theme.spacing(2),
[theme.breakpoints.up('sm')]: {
display: 'none',
},
},
toolbar: theme.mixins.toolbar,
drawerPaper: {
width: drawerWidth
},
content: {
flexGrow: 1,
padding: theme.spacing(0),
},
closeMenuButton: {
marginRight: 'auto',
marginLeft: 0,
},
}));
function NavBar() {
const DifferentPages = [
{Text: "Home", location: "/", Image: home},
{Text: "About", location: "/about", Image: about},
{Text: "Contact", location: "/contact", Image: contact},
{Text: "Resume", location: "/resume", Image: resume},
{Text: "Minecraft", location: "/minecraft", Image: minecraft},
]
const classes = useStyles();
const theme = useTheme();
const [mobileOpen, setMobileOpen] = React.useState(false);
function handleDrawerToggle() {
setMobileOpen(!mobileOpen)
}
const drawer = (
<div>
<List>
{DifferentPages.map((Text) => (
<ListItem button component={Link} to={Text.location}>
<img src={Text.Image} width={"25"} height={"25"}/>
<ListItemText primary={Text.Text} />
</ListItem>
))}
<ListItem button href={"example.com"}>
<img src={github} width={"25"} height={"25"}/>
<ListItemText>
Github
</ListItemText>
</ListItem>
</List>
</div>
);
return (
<div className={classes.root}>
<CssBaseline />
<AppBar position="fixed" className={classes.appBar}>
<Toolbar>
<IconButton
color="inherit"
aria-label="Open drawer"
edge="start"
onClick={handleDrawerToggle}
className={classes.menuButton}
>
<MenuIcon />
</IconButton>
<Typography variant="h6" noWrap>
Responsive drawer
</Typography>
</Toolbar>
</AppBar>
<nav className={classes.drawer}>
<Hidden smUp implementation="css">
<Drawer
variant="temporary"
anchor={theme.direction === 'rtl' ? 'right' : 'left'}
open={mobileOpen}
onClose={handleDrawerToggle}
classes={{
paper: classes.drawerPaper,
}}
ModalProps={{
keepMounted: true, // Better open performance on mobile.
}}
>
<IconButton onClick={handleDrawerToggle} className={classes.closeMenuButton}>
<CloseIcon/>
</IconButton>
{drawer}
</Drawer>
</Hidden>
<Hidden xsDown implementation="css">
<Drawer
className={classes.drawer}
variant="permanent"
classes={{
paper: classes.drawerPaper,
}}
>
<div className={classes.toolbar} />
{drawer}
</Drawer>
</Hidden>
</nav>
<div className={classes.content}>
<div className={classes.toolbar} />
</div>
</div>
);
}
NavBar.propTypes = {
container: PropTypes.object,
};
export default NavBar;
App.js: NOTE** in App.js, I can add style={{paddingleft:240}} to the div before routes and it kind of remedy this issue, however, once the screen is small enough (i.e.like mobile) view and the drawer is hidden, 240px padding is still there.
(edited down for simplicity - content still the same)
import React from 'react';
import './App.css';
import { HashRouter as Router, Routes, Route} from 'react-router-dom';
//Page Routes
import NavigationAppBar from "./Navigation-Bar/NavigationAppBar";
import Home from './Page-Information/main';
function App() {
return (
<Router>
<NavigationAppBar/>
<div>
<Routes>
<Route exact path='/' exact element={<Home />} />
</Routes>
</div>
</Router>
);
}
export default App;
Home.js: (edited down for simplicity - content still the same)
import React from 'react';
const Home = () => {
return (
<div>
<h3>Example</h3>
</div>
);
};
export default Home;
I have forked the default persistent demo updated it into separate files.
You can add breakpoint for smaller device to remove margin or padding as appropriate.
const Main = styled("main", { shouldForwardProp: (prop) => prop !== "open" })(
({ theme, open }) => ({
flexGrow: 1,
padding: theme.spacing(3),
transition: theme.transitions.create("margin", {
easing: theme.transitions.easing.sharp,
duration: theme.transitions.duration.leavingScreen
}),
marginLeft: `-${drawerWidth}px`,
...(open && {
transition: theme.transitions.create("margin", {
easing: theme.transitions.easing.easeOut,
duration: theme.transitions.duration.enteringScreen
}),
marginLeft: 0
}),
[theme.breakpoints.down('sm')]: {
//add CSS here.
}
})
);
i have inertia progress bar initialized in my app.js
app.js
import React from "react";
import { render } from "react-dom";
import { createInertiaApp } from "#inertiajs/inertia-react";
import { InertiaProgress } from "#inertiajs/progress";
createInertiaApp({
resolve: (name) => require(`./Pages/${name}`),
setup({ el, App, props }) {
render(<App {...props} />, el);
},
});
InertiaProgress.init({
// The color of the progress bar.
color: "red",
// Whether the NProgress spinner will be shown.
showSpinner: true,
});
but the progressbar won't appear every time I render the appbar in the layout, its only the layout file, because if I render without it The progressbar will appear as usual
here is my Layout.tsx
import {
Button,
Container,
ListItem,
ListItemIcon,
ListItemText,
useTheme,
} from "#mui/material";
import React from "react";
import { styled, ThemeProvider } from "#mui/material/styles";
import CssBaseline from "#mui/material/CssBaseline";
import MuiDrawer from "#mui/material/Drawer";
import Box from "#mui/material/Box";
import MuiAppBar, { AppBarProps as MuiAppBarProps } from "#mui/material/AppBar";
import Toolbar from "#mui/material/Toolbar";
import List from "#mui/material/List";
import Typography from "#mui/material/Typography";
import Divider from "#mui/material/Divider";
import IconButton from "#mui/material/IconButton";
import MenuIcon from "#mui/icons-material/Menu";
import ChevronLeftIcon from "#mui/icons-material/ChevronLeft";
import { listItems } from "./ListItems";
import { usePage } from "#inertiajs/inertia-react";
import { Inertia } from "#inertiajs/inertia";
import route from "ziggy-js";
import FlashMessage from "./FlashMessage";
import { withStyles } from "#mui/styles";
const Layout = ({
children,
title,
}: {
children: React.ReactNode;
title: React.ReactNode;
}) => {
const theme = useTheme();
const authUser: any = usePage().props.user;
const drawerWidth: number = 240;
interface AppBarProps extends MuiAppBarProps {
open?: boolean;
}
const [open, setOpen] = React.useState(false);
const toggleDrawer = () => {
setOpen(!open);
};
const handleLogout = () => {
if (confirm("are you sure want to logout?")) {
Inertia.post(route("logout"));
}
};
return (
<ThemeProvider theme={theme}>
<Box sx={{ display: "flex" }}>
<CssBaseline />
<AppBar position="absolute" open={open}>
<Toolbar
sx={{
pr: "24px", // keep right padding when drawer closed
}}
>
<IconButton
edge="start"
color="inherit"
aria-label="open drawer"
onClick={toggleDrawer}
sx={{
marginRight: "36px",
...(open && { display: "none" }),
}}
>
<MenuIcon />
</IconButton>
<Typography
component="h1"
variant="h6"
color="inherit"
noWrap
sx={{ flexGrow: 1, marginLeft: 2 }}
>
{title}
</Typography>
<Button
{...(authUser ? { display: "none" } : { sx: {} })}
variant="text"
color="inherit"
onClick={handleLogout}
>
Logout
</Button>
</Toolbar>
</AppBar>
<Drawer variant="permanent" open={open}>
<Toolbar
sx={{
display: "flex",
alignItems: "center",
justifyContent: "flex-end",
px: [1],
}}
>
<IconButton onClick={toggleDrawer}>
<ChevronLeftIcon />
</IconButton>
</Toolbar>
<Divider />
<List>{listItems}</List>
</Drawer>
<Box
component="main"
}}
>
<Toolbar />
<FlashMessage />
<Container sx={{ marginTop: "50px" }}>{children}</Container>
</Box>
</Box>
</ThemeProvider>
);
};
export default Layout;
I think my progressbar appears under the appbar, is there any solution to this problem?
Just find out what the zIndex for your AppBar is (1100 by default I think)
console.log(Theme.zIndex.appBar)
Then on your CSS file, add a line to make the zIndex of the progress bar higher:
#nprogress .bar {
z-index: 1101!important;
}
I am using material ui with react I want to know that
How can I change the background color of my card component when a user hovers?
Here is my live code link in codeasandbox.
Below I also put my code.
MyCard.js Here I want to change the background color on hover so the padding area changes the color
import React from "react";
import { makeStyles } from "#material-ui/core/styles";
import Card from "#material-ui/core/Card";
import CardActionArea from "#material-ui/core/CardActionArea";
import CardMedia from "#material-ui/core/CardMedia";
const useStyles = makeStyles((theme) => ({
root: {
// maxWidth: 345,
margin: theme.spacing(0.5),
padding: theme.spacing(0.8),
borderRadius: theme.spacing(0),
"& :hover": {
backgroundColor: "green"
}
},
media: {
height: 140
}
}));
export default function MyCard() {
const classes = useStyles();
return (
<Card className={classes.root} elevation={3}>
<CardActionArea>
<CardMedia
className={classes.media}
image="https://images.pexels.com/photos/2787341/pexels-photo-2787341.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=650&w=940"
title="Face"
/>
</CardActionArea>
</Card>
);
}
You should try omitting that space in on hover property, and write "&:hover" rather than "&(space):hover". It works fine in your sandbox code.
With the help of Y.S. I figured out it was just a typo having extra space near &
Here is the working code
import React from "react";
import { makeStyles } from "#material-ui/core/styles";
import Card from "#material-ui/core/Card";
import CardActionArea from "#material-ui/core/CardActionArea";
import CardMedia from "#material-ui/core/CardMedia";
import { Paper } from "#material-ui/core";
const useStyles = makeStyles((theme) => ({
root: {
// maxWidth: 345,
margin: theme.spacing(0.5),
padding: theme.spacing(0.8),
borderRadius: theme.spacing(0),
"&:hover": {
backgroundColor: "green"
}
},
media: {
height: 140
}
}));
export default function MyCard() {
const classes = useStyles();
return (
<Card className={classes.root} elevation={3}>
<CardActionArea>
<CardMedia
className={classes.media}
image="https://images.pexels.com/photos/2787341/pexels-photo-2787341.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=650&w=940"
title="Face"
/>
</CardActionArea>
</Card>
);
}
I'm building an app using function based component. I found the sidebar menu template from Material Ui in classes and want to convert it to functional component. But after converting click button doesn't work. I've only changed the menu icon to another.
Any help will be appreciated.
Here is the default component in classes
import React from "react";
import AppBar from "#material-ui/core/AppBar";
import Toolbar from "#material-ui/core/Toolbar";
import Typography from "#material-ui/core/Typography";
import Button from "#material-ui/core/Button";
import IconButton from "#material-ui/core/IconButton";
import MenuIcon from "#material-ui/icons/Menu";
import { NavDrawer } from "./NavDrawer";
class NavBar extends React.Component {
constructor(props) {
super(props);
this.state = {
drawerOpened: false
};
}
toggleDrawer = booleanValue => () => {
this.setState({
drawerOpened: booleanValue
});
};
render() {
return (
<div className="App">
<AppBar position="static">
<Toolbar>
<IconButton
color="secondary"
aria-label="Menu"
onClick={this.toggleDrawer(true)}
>
<MenuIcon />
</IconButton>
<Typography variant="h6" color="inherit">
News
</Typography>
<Button color="inherit">Login</Button>
</Toolbar>
</AppBar>
<NavDrawer
drawerOpened={this.state.drawerOpened}
toggleDrawer={this.toggleDrawer}
/>
</div>
);
}
}
export default NavBar
Here I'm trying to convert
import React, { useState } from 'react'
import AppBar from '#material-ui/core/AppBar'
import Toolbar from '#material-ui/core/Toolbar'
import Typography from '#material-ui/core/Typography'
import IconButton from '#material-ui/core/IconButton'
import NavDrawer from './NavDrawer'
import AddShoppingCartIcon from '#material-ui/icons/AddShoppingCart'
function NavBar(props) {
const [drawerOpened, setDrawerOpened] = useState(false)
const toggleDrawer = booleanValue => () => {
setDrawerOpened(booleanValue)
}
return (
<div className="App">
<AppBar position="static">
<Toolbar>
<IconButton
aria-label="AddShoppingCartIcon"
onClick={() => toggleDrawer(true)}
>
<AddShoppingCartIcon style={{ fontSize: 30 }} color="secondary" />
</IconButton>
<Typography variant="h6" color="inherit"></Typography>
</Toolbar>
</AppBar>
<NavDrawer drawerOpened={drawerOpened} toggleDrawer={toggleDrawer} />
</div>
)
}
export default NavBar
Have a look at React hooks, there ae two approaches:
const [toggleDrawer, setToggleDrawer] = useState(false); // set variable
<button onClick={() => setToggleDrawer(!toggleDrawer}>
Of you can useEffect to perform some logic after the component is initially rendered, preventing a max error:
const toggleDrawer = false;
useEffect(() => { // update variable
checkDrawOpened(toggleDrawer)
}, toggleDrawer);]
With the one click
onClick={toggleDrawer} // use variable
You can do this instead for toggling actions.
const toggleDrawer = () => {
setDrawerOpened(!drawerOpened)
}
And in the return
onClick={toggleDrawer}
Your function is stacking. On onclick, you try to call function to call function. Just use the const instead.
on toggleDrawer const, you should set setDrawerOpened to whenever the opposite of value it is to get toggling effect.
I am working in react and try to build a page for this web app that displays data.
I haven't even been able to get it to display the data for this page yet.
The code that I need to pull is from a web link, I need to pull that and display it on a card with material UI.
import React, { Component } from 'react';
import Card from '#material-ui/core/Card';
import CardContent from '#material-ui/core/CardContent';
import Paper from '#material-ui/core/Paper';
import Typography from '#material-ui/core/Typography';
import PropTypes from 'prop-types';
import { withStyles } from '#material-ui/core/styles';
const STYLES = {
card: {
minWidth: 275,
},
//bullet: {
//display: 'inline-block',
//margin: '0 2px',
//transform: 'scale(0.8)',
//},
//title: {
//marginBottom: 16,
//fontSize: 14,
//},
//pos: {
// marginBottom: 12,
//},
};
class ErrorView extends Component{
constructor(props) {
super(props);
this.extractErrorData = this.extractErrorData.bind(this)
}
extractErrorData(errorDatas) {
return errorDatas.map((errorViewData) => {
<Card>
<CardContent>
{'errorData.project'}
</CardContent>
<CardContent>
{'errorData.errorText'}
</CardContent>
</Card>
})
}
render() {
const { header, errorViewData } = this.props;
return (
<Paper elevation={4} Color='#fff'>
<Typography variant="headline" component="h3">
{header}
</Typography>
{this.extractErrorData(errorViewData)}
</Paper>
);
}
}
ErrorView = {
classes: PropTypes.object.isRequired,
};
export default withStyles(STYLES)(ErrorView);
Remove the single quotes in extractErrorData if you want to show errorData.project and errorData.errorText values (and rename errorData with errorViewData):
extractErrorData(errorDatas) {
return errorDatas.map((errorViewData) => {
<Card>
<CardContent>
{errorViewData.project}
</CardContent>
<CardContent>
{errorViewData.errorText}
</CardContent>
</Card>
})
}
Note: you should add a JSFiddle or write something more to let us better understand what the problem is.