Applying css on a imported react component - css

I have a UserPreview component which have other components( avatar, bio, followstats). When, I am trying to style these components, nothing happens. I tried inline styling as well. But, Styling on a normal div is working perfectly fine. I have no idea why its happening.
import React from "react";
import Avatar from "../../Atoms/Avatar";
import Bio from "../../Atoms/Bio";
import FollowStats from "../../Atoms/FollowStats";
import Profile from "../../Assets/images/profile.jpg";
import useStyles from "./style";
const UserPreview = () => {
const classes = useStyles();
return (
<div className={classes.root}>
<Avatar
size="large"
image={Profile}
name="Aman"
username="dev_aman7"
className={classes.avatar}
style={{ border: "1px solid red" }}
/>
<Bio value="This is Bio" className={classes.bio} />
<div className={classes.edit}>Edit Profile</div>
<FollowStats followers={20} following={30} className={classes.follow} />
</div>
);
};
export default UserPreview;
Styles
import makeStyles from "#material-ui/styles/makeStyles";
const useStyles = makeStyles((theme) => ({
root: {
display: "flex",
alignItems: "center",
maxWidth: "20rem",
flexDirection: "column",
paddingTop: "1rem",
},
avatar: {
padding: "5rem",
border: "1px solid black",
},
bio: {
marginTop: "1rem",
},
edit: {
color: theme.palette.blue,
fontSize: theme.f5,
margin: "auto",
marginTop: ".5rem",
},
follow: {
margin: "1.5rem",
width: "100%",
},
}));
export default useStyles;
Material ui is used as design library
Avatar.jsx
import React from "react";
import ClassNames from "classnames";
import PropTypes from "prop-types";
import useStyles from "./style";
const Avatar = ({ image, size, name, username }) => {
const classes = useStyles();
const container = ClassNames(
{ [classes.root_small]: size === "small" },
{ [classes.root_large]: size !== "small" }
);
const usernameClass = ClassNames(classes.username, {
[classes.grey]: size === "small",
});
const imgClass = ClassNames(
classes.img,
{ [classes.img_small]: size === "small" },
{ [classes.img_large]: size !== "small" }
);
return (
<div className={container}>
<div>
<img src={image} alt="Profile_image" className={imgClass} />
</div>
{size === "small" ? null : <div className={classes.name}>{name}</div>}
<div className={usernameClass}>#{username}</div>
</div>
);
};
Avatar.defaultProps = { name: "" };
Avatar.propTypes = {
image: PropTypes.string.isRequired,
size: PropTypes.string.isRequired,
name: PropTypes.string,
username: PropTypes.string.isRequired,
};
export default Avatar;
import { makeStyles } from "#material-ui/styles";
const useStyles = makeStyles((theme) => ({
root_small: {
display: "flex",
alignItems: "center",
},
root_large: {
maxWidth: "20rem",
textAlign: "center",
},
img: {
borderRadius: "50%",
},
img_small: {
height: "2.5rem",
width: "2.5rem",
marginRight: "1rem",
},
img_large: { width: "4.5rem", height: "4.5rem" },
name: {
fontSize: theme.f2,
fontWeight: theme.bold6,
marginTop: "0.5rem",
color: theme.palette.grey,
},
username: {
fontSize: theme.f4,
color: theme.palette.pinkGrey,
},
grey: {
color: theme.palette.grey,
},
}));
export default useStyles;

Related

How to change styles in Table Pagination Material-ui v.5.0 with React

I'm trying to change the width, height and color of table pagination on Material-ui V5.0 with React, but it does not accept classes. As the pagination uses .MuiToolbar-root, if I make changes with a .css file, it brakes my MuiToolbar at the top of the App page. How should I apply the changes needed without braking the Appbar at the top? Also, I will need to change the padding of .MuiTableCell-root as well. I'm sending my code bellow. Please all helps will be very appreciated.
// Component SupplierTable
import React, {useState} from 'react'
import './SupplierTable.css';
import SupplierForm from './SupplierForm';
import PageHeader from '../components/PageHeader';
import FactoryIcon from '#mui/icons-material/Factory';
import * as supplierService from '../services/EmployeeService';
import Controls from "../components/controls/Controls";
import { InputAdornment } from '#mui/material';
import SearchIcon from '#mui/icons-material/Search';
import AddIcon from '#mui/icons-material/Add';
import Box from '#mui/material/Box';
import Paper from '#mui/material/Paper';
import useTable from "../components/useTable";
import { makeStyles } from '#mui/styles';
import ModeEditOutlineIcon from '#mui/icons-material/ModeEditOutline';
import { TableRow, TableBody, TableCell } from '#mui/material';
import CloseIcon from '#mui/icons-material/Close';
import Popup from '../components/Poup';
import Notification from '../components/Notifications';
import ConfirmDialog from '../components/ConfirmDialog';
import Grid from '#mui/material/Grid';
const useStyles = makeStyles(theme => ({
overrides: {
'&.MuiTablePagination-root':{
width: '960px',
height: '35px',
backgroundColor: '#a9aeb3',
color: 'rgb(41, 39, 39)',
fontFamily: 'Arial, Helvetica, sansSerif',
fontWeight: '700',
}
},
pageContent: {
margin: theme.spacing(1),
padding: theme.spacing(3)
},
searchInput: {
width: '50%'
},
newButton: {
position: 'absolute',
right: '0px'
},
}));
const headCells = [
{ id: 'fullName', label: 'Employee Name' },
{ id: 'email', label: 'Email Address (Personal)' },
{ id: 'mobile', label: 'Mobile Number' },
{ id: 'department', label: 'Department' },
{ id: 'actions', label: 'Actions', disableSorting: true }
]
export default function Supplyer() {
const classes = useStyles();
const [recordForEdit, setRecordForEdit] = useState(null)
const [records, setRecords] = useState(supplierService.getAllSuppliers())
const [filterFn, setFilterFn] = useState({ fn: items => { return items; } })
const [openPopup, setOpenPopup] = useState(false)
const [notify, setNotify] = useState({ isOpen: false, message: '', type: '' })
const [confirmDialog, setConfirmDialog] = useState({ isOpen: false, title: '', subTitle: '' })
const {
TblContainer,
TblHead,
TblPagination,
recordsAfterPagingAndSorting
} = useTable(records, headCells, filterFn);
const handleSearch = e => {
let target = e.target;
setFilterFn({
fn: items => {
if (target.value == "")
return items;
else
return items.filter(x => x.fullName.toLowerCase().includes(target.value))
}
})
}
const addOrEdit = (employee, resetForm) => {
if (employee.id == 0)
supplierService.insertEmployee(employee)
else
supplierService.updateEmployee(employee)
resetForm()
setRecordForEdit(null)
setOpenPopup(false)
setRecords(supplierService.getAllEmployees())
setNotify({
isOpen: true,
message: 'Submitted Successfully',
type: 'success'
})
}
const openInPopup = item => {
setRecordForEdit(item)
setOpenPopup(true)
}
const onDelete = id => {
setConfirmDialog({
...confirmDialog,
isOpen: false
})
supplierService.deleteEmployee(id);
setRecords(supplierService.getAllEmployees())
setNotify({
isOpen: true,
message: 'Deleted Successfully',
type: 'error'
})
}
return (
<>
<PageHeader
title= "Fornecedores"
subTitle="Tabela de Fornecedores - Novo / Atualizar"
icon={<FactoryIcon fontSize="large" text-align='center'/>}
/>
<Box sx={{width: "1060px"}}>
<Paper className={classes.pageContent}>
<Grid container direction= 'row' justifyContent="space-between" >
<Controls.Input
label="Pesquisar Fornecedor"
className={classes.searchInput}
InputProps={{
startAdornment: (<InputAdornment position="start">
<SearchIcon />
</InputAdornment>)
}}
onChange={handleSearch}
/>
<Controls.Button
text="Adicionar"
variant="outlined"
color="primary"
startIcon={<AddIcon />}
className={classes.newButton}
onClick={() => { setOpenPopup(true); setRecordForEdit(null); }}
/>
</Grid>
<TblContainer>
<TblHead />
<TableBody>
{
recordsAfterPagingAndSorting().map(item =>
(<TableRow key={item.id}>
<TableCell>{item.fullName}</TableCell>
<TableCell>{item.email}</TableCell>
<TableCell>{item.mobile}</TableCell>
<TableCell>{item.department}</TableCell>
<TableCell>
<Controls.ActionButton
color="primary"
onClick={() => { openInPopup(item) }}>
<ModeEditOutlineIcon fontSize="small" />
</Controls.ActionButton>
<Controls.ActionButton
color="secondary"
onClick={() => {
setConfirmDialog({
isOpen: true,
title: 'Are you sure to delete this record?',
subTitle: "You can't undo this operation",
onConfirm: () => { onDelete(item.id) }
})
}}>
<CloseIcon fontSize="small" />
</Controls.ActionButton>
</TableCell>
</TableRow>)
)
}
</TableBody>
</TblContainer>
**strong text** // Pagination begins here!!!!!
<TblPagination components={{
Toolbar: props => (
<div>
style={{ backgroundColor: '#a9aeb3', width: '950px', color: 'rgb(41, 39, 39)',
height: '35px' }}
</div>
)
}}/>
</Paper>
</Box>
<Popup
title="Employee Form"
openPopup={openPopup}
setOpenPopup={setOpenPopup}
>
<SupplierForm
recordForEdit={recordForEdit}
addOrEdit={addOrEdit} />
</Popup>
<Notification
notify={notify}
setNotify={setNotify}
/>
<ConfirmDialog
confirmDialog={confirmDialog}
setConfirmDialog={setConfirmDialog}
/>
</>
)
}
I've been struggling with styling the pagination component myself, but just got it working using sx.
Try with something like this:
<TablePagination
sx={{
'.MuiTablePagination-toolbar': {
backgroundColor: '#a9aeb3',
width: '950px',
color: 'rgb(41, 39, 39)',
height: '35px',
},
}}
/>
Edit:
I tried styling "everything" just to see how it would be done, look here for ideas if there was something else you needed to style.
<Pagination
{...mTablePaginationProps}
rowsPerPage={rowsPerPage}
onRowsPerPageChange={onRowsPerPageSelect}
component="div"
onPageChange={onPageChange}
sx={{
backgroundColor: 'red !important', // gets overridden if not important
height: '70px',
'.MuiInputBase-root': {
backgroundColor: 'green',
},
'.MuiTablePagination-toolbar': {
backgroundColor: 'pink',
width: '950px',
color: 'rgb(41, 39, 39)',
height: '35px',
},
'.MuiBox-root': {
backgroundColor: 'yellow',
color: 'black',
'& .MuiSvgIcon-root': {
backgroundColor: 'purple',
color: 'black',
},
},
}}
SelectProps={{
...mTablePaginationProps.SelectProps,
MenuProps: {
...mTablePaginationProps.SelectProps.MenuProps,
sx: {
'.MuiPaper-root': {
backgroundColor: 'rosybrown',
color: 'black',
},
'.MuiTablePagination-menuItem': {
':hover': {
backgroundColor: 'turquoise',
},
backgroundColor: 'yellow',
},
'.MuiTablePagination-menuItem.Mui-selected': {
':hover': {
backgroundColor: 'blue',
},
backgroundColor: 'purple',
},
},
},
}}
/>
This ends up looking like this:

Setting default backgroud color in nextjs react app

I want to set a default background color that will apply to all created pages in my project.
I have tried the following tutorial: https://itnext.io/next-js-with-material-ui-7a7f6485f671 but it does not work and gives this error: Error
Here are my files:
Index.tsx file:
import LoginPage from "./login";
export default function Start() {
return (<div ><LoginPage></LoginPage></div>);
}
Login.tsx file
import Typography from "#mui/material/Typography"
import React from 'react';
import { makeStyles } from '#mui/styles';
import { Button, TextField } from "#mui/material";
const useStyles = makeStyles(theme => ({
root: {
display: "inline-grid",
margin: "auto",
position:"fixed",
top: "50%",
left: "50%",
width:"30em",
height:"18em",
marginTop: "-9em",
marginLeft: "-15em",
border: "1px solid #ccc",
},
loginButton: {
border: "1px solid #ccc",
width: "30%",
height: "80%",
margin: "auto"
},
loginText: {
margin: "auto"
}
}));
export default function LoginPage() {
const classes = useStyles();
return (
<>
<div className={classes.root}>
<Typography className ={classes.loginText}>Login</Typography>
<TextField id="filled-basic" label="Email Adresse" variant="standard"></TextField>
<TextField id="filled-basic" label="Passwort" variant="standard" />
<Button className={classes.loginButton}>Login</Button>
</div>
</>
);
}
useTheme.ts file:
import { createTheme } from "#mui/material/styles";
// Create a theme instance.
const theme = createTheme ({
palette: {
primary: {
main: '#556cd6',
},
secondary: {
main: '#19857b',
},
background: {
default: '#fff',
},
},
});
export default theme;
_app.tsx and _document.tsx are the same as in the tutorial provided in the link above
That's how my folder looks like with all files in
How can I fix the error that I am getting?

How can I scroll on my Page when my Dialog Component has been opened

I want to scroll on the background, when my dialog component opens up. By default, you cannot scroll when the dialog appears. How can I scroll in the background ?
Following is the Code:-
import React, { useState } from 'react';
import {
makeStyles,
Grid,
Button,
Dialog,
DialogActions,
DialogTitle,
} from '#material-ui/core';
import ShoppingCartIcon from '#material-ui/icons/ShoppingCart';
import CloseIcon from '#material-ui/icons/Close';
const styles = makeStyles((theme) => ({
root: {
position: 'fixed',
bottom: '0 ',
left: '0',
right: '0',
boxShadow: '0 0 6px rgb(0 0 0 / 70%)',
backgroundColor: 'white',
height: '63px',
},
textStyle: {
fontFamily: 'Comfortaa',
},
icon: {
color: theme.palette.primary.dark,
},
btn: {
backgroundColor: theme.palette.primary.dark,
color: 'white',
fontFamily: 'Comfortaa',
'&:hover': {
backgroundColor: theme.palette.primary.dark,
},
},
title: {
display: 'flex',
justifyContent: 'flex-end',
borderBottom: '1px solid #e5e5e5',
},
closeIcon: {
color: theme.palette.primary.light,
'&:hover': {
color: 'black',
},
},
dialogStyle: {
backgroundColor: 'white',
position: 'absolute',
top: 0,
},
dialogContainer: {
opacity: 0,
},
dialogTitle: {
display: 'flex',
justifyContent: 'flex-end',
borderBottom: '1px solid #e5e5e5',
},
}));
const CartAppBar: React.FC = () => {
const classes = styles();
const [open, setOpen] = useState(false);
const handleClickOpen = () => {
setOpen(true);
};
const handleClose = () => {
setOpen(false);
};
return (
<>
<Grid
item
container
direction='row'
justify='space-around'
alignItems='center'
className={classes.root}
xs={12}
>
<div>
<ShoppingCartIcon
fontSize='large'
classes={{ root: classes.icon }}
onClick={handleClickOpen}
/>
</div>
<div>
<Button
className={classes.btn}
type='submit'
onClick={() => {
return (window.location.href = '/checkout');
}}
>
Checkout
</Button>
</div>
</Grid>
<Dialog
open={open}
onClose={handleClose}
aria-labelledby='alert-dialog-title'
aria-describedby='alert-dialog-description'
maxWidth='md'
fullWidth
classes={{
paper: classes.dialogStyle,
container: classes.dialogContainer,
}}
scroll='paper'
>
<DialogTitle className={classes.dialogTitle}>
<CloseIcon
onClick={handleClose}
classes={{ root: classes.closeIcon }}
/>
</DialogTitle>
{/* Footer */}
{/* <DialogActions className={classes.footer}>
<Button classes={{ root: classes.btn }}>Add To Cart</Button>
</DialogActions> */}
</Dialog>
</>
);
};
export default CartAppBar;
As you can see in the photo, there's opacity in the background and you cannot scroll. I want to override this and make the background scrollable
use disableScrollLock as prop will help

How to change border color of material ui Rating stars

I need to change the border color of stars in material ui Rating cause my background color is black and I can't see nothing when the star is empty !
code:
import Rating from '#material-ui/lab/Rating';
import { makeStyles } from '#material-ui/core/styles';
const useStyles = makeStyles((theme) => ({
root: {
display: 'flex',
flexDirection: 'column',
'& > * + *': {
marginTop: theme.spacing(1),
},
},
}));
in the functional component :
<div className={classes.root}>
<Rating name="half-rating-read" defaultValue={finalAverage} precision={0.5} readOnly />
</div>
you need to import an icon with border for empty one like StarBorderIcon and add it like this:
import Rating from "#material-ui/lab/Rating";
import StarBorderIcon from "#material-ui/icons/StarBorder";
import { makeStyles } from "#material-ui/core/styles";
const useStyles = makeStyles((theme) => ({
root: {
display: "flex",
flexDirection: "column",
"& > * + *": {
marginTop: theme.spacing(1)
}
},
emptyStar: {
color: "white"
}
}));
const Star = () => {
const classes = useStyles();
return (
<div className={classes.root}>
<Rating
name="half-rating-read"
defaultValue={3.5}
precision={0.5}
readOnly
emptyIcon={
<StarBorderIcon fontSize="inherit" className={classes.emptyStar} />
}
/>
</div>
);
};
export default Star;

Properly pushing a Canvas with Material UI Persistent Drawers

I have an application with two expandable toolbars. The left toolbar functions as intended, but I have not been able to make the right toolbar push the content properly. See the code below.
I copied the exact code from here - see Persistent Drawers: https://material-ui.com/demos/drawers/
The KeyboardListener is display:none and the SceneCanvas element has the following styling:
root: {
height: '100%',
width: '100%',
position: 'relative',
zIndex: 0,
lineHeight: 0,
cursor: 'crosshair',
}
The desired functionality is for both the left and right toolbars to push the content in and resize the canvas and the canvas content. And tips or insight would be greatly appreciated!
import React from 'react';
import classNames from 'classnames';
import { withStyles } from '#material-ui/core/styles';
import Drawer from '#material-ui/core/Drawer';
import AppBar from '#material-ui/core/AppBar';
import Toolbar from '#material-ui/core/Toolbar';
import List from '#material-ui/core/List';
import MenuItem from '#material-ui/core/MenuItem';
import Typography from '#material-ui/core/Typography';
import TextField from '#material-ui/core/TextField';
import Divider from '#material-ui/core/Divider';
import IconButton from '#material-ui/core/IconButton';
import MenuIcon from '#material-ui/icons/Menu';
import ChevronLeftIcon from '#material-ui/icons/ChevronLeft';
import ChevronRightIcon from '#material-ui/icons/ChevronRight';
import SceneCanvas from '../../three/SceneCanvas';
import KeyboardListener from '../KeyboardListener';
const drawerWidth = 240;
const styles = theme => ({
root: {
flexGrow: 1,
},
appFrame: {
height: 430,
zIndex: 1,
overflow: 'hidden',
position: 'relative',
display: 'flex',
width: '100%',
},
appBar: {
position: 'absolute',
transition: theme.transitions.create(['margin', 'width'], {
easing: theme.transitions.easing.sharp,
duration: theme.transitions.duration.leavingScreen,
}),
},
appBarShift: {
width: `calc(100% - ${drawerWidth}px)`,
transition: theme.transitions.create(['margin', 'width'], {
easing: theme.transitions.easing.easeOut,
duration: theme.transitions.duration.enteringScreen,
}),
},
'appBarShift-left': {
marginLeft: drawerWidth,
},
'appBarShift-right': {
marginRight: drawerWidth,
},
menuButton: {
marginLeft: 12,
marginRight: 20,
},
hide: {
display: 'none',
},
drawerPaper: {
position: 'relative',
width: drawerWidth,
},
drawerHeader: {
display: 'flex',
alignItems: 'center',
justifyContent: 'flex-end',
padding: '0 8px',
...theme.mixins.toolbar,
},
content: {
flexGrow: 1,
backgroundColor: theme.palette.background.default,
padding: theme.spacing.unit * 3,
transition: theme.transitions.create('margin', {
easing: theme.transitions.easing.sharp,
duration: theme.transitions.duration.leavingScreen,
}),
},
'content-left': {
marginLeft: -drawerWidth,
},
'content-right': {
marginRight: -drawerWidth,
},
contentShift: {
transition: theme.transitions.create('margin', {
easing: theme.transitions.easing.easeOut,
duration: theme.transitions.duration.enteringScreen,
}),
},
'contentShift-left': {
marginLeft: 0,
},
'contentShift-right': {
marginRight: 0,
},
});
class Header extends React.Component {
state = {
open: false,
anchor: 'left',
};
handleDrawerOpen = () => {
this.setState({ open: true });
};
handleDrawerClose = () => {
this.setState({ open: false });
};
handleChangeAnchor = (event) => {
this.setState({
anchor: event.target.value,
});
};
render() {
const { classes, theme } = this.props;
const { anchor, open } = this.state;
const drawer = (
<Drawer
variant="persistent"
anchor={anchor}
open={open}
classes={{
paper: classes.drawerPaper,
}}
>
<div className={classes.drawerHeader}>
<IconButton onClick={this.handleDrawerClose}>
{theme.direction === 'rtl' ? <ChevronRightIcon /> : <ChevronLeftIcon />}
</IconButton>
</div>
<Divider />
<List>Testing</List>
<Divider />
<List>Testing</List>
</Drawer>
);
let before = null;
let after = null;
if (anchor === 'left') {
before = drawer;
} else {
after = drawer;
}
return (
<div className={classes.root}>
<TextField
id="persistent-anchor"
select
label="Anchor"
value={anchor}
onChange={this.handleChangeAnchor}
margin="normal"
>
<MenuItem value="left">left</MenuItem>
<MenuItem value="right">right</MenuItem>
</TextField>
<div className={classes.appFrame}>
<AppBar
className={classNames(classes.appBar, {
[classes.appBarShift]: open,
[classes[`appBarShift-${anchor}`]]: open,
})}
>
<Toolbar disableGutters={!open}>
<IconButton
color="inherit"
aria-label="open drawer"
onClick={this.handleDrawerOpen}
className={classNames(classes.menuButton, open && classes.hide)}
>
<MenuIcon />
</IconButton>
<Typography variant="title" color="inherit" noWrap>
Persistent drawer
</Typography>
</Toolbar>
</AppBar>
{before}
<main
className={classNames(classes.content, classes[`content-${anchor}`], {
[classes.contentShift]: open,
[classes[`contentShift-${anchor}`]]: open,
})}
>
<div className={classes.drawerHeader} />
<KeyboardListener />
<SceneCanvas />
</main>
{after}
</div>
</div>
);
}
}
export default withStyles(styles, { withTheme: true })(Header);
Left Toolbar Functioning Properly
Right Toolbar Breaking
Desired Function

Resources