How to optimize Components in React? - javascript

In a React project, I have certain Pages/Components which has common structure with few variations. See the code below for clarity
const navScrollStyle = makeStyles((theme) => ({
root: {
marginTop: "120px",
display: "table",
overflowY: "auto",
maxWidth: "auto",
display: "flex",
justifyContent: "center"
}
}));
const navBodyStyle = makeStyles((theme) => ({
root: {
flexGrow: 1,
top: "0px",
position: "absolute",
width: "100%",
height: "100vh",
textAlign: "center",
background: "white",
zIndex: "9999",
height: "100%",
overflowY: "auto"
},
menuButton: {
marginRight: theme.spacing(2),
color: "purple"
},
title: {
flexGrow: 1,
textAlign: "center",
color: "black"
}
}));
const gridClassStyle = makeStyles((theme) => ({
root: {
zIndex: "100",
flexGrow: 1,
position: "fixed",
top: "0px",
background: "white",
flexWrap: "nowrap",
boxShadow: "5px 10px 18px #888888"
}
}));
const FAQ = () => {
const navBody = navBodyStyle();
const navScroll = navScrollStyle();
const gridClass = gridClassStyle();
const NavPart = () => (
<Grid className={gridClass.root} container spacing={3}>
<BackButton />
<NameHeader name="FAQ" /> {/* <-- Here name changes */}
<AccountIcon />
</Grid>
);
return (
<div className={navBody.root}>
{NavPart()}
<div className={navScroll.root}>
<h2>This is FAQ Section</h2> {/* <-- And the body part too */}
</div>
</div>
);
};
export default FAQ;
Above is the FAQ page
Take another page
const navScrollStyle = makeStyles((theme) => ({
root: {
marginTop: "120px",
display: "table",
overflowY: "auto",
maxWidth: "auto",
display: "flex",
justifyContent: "center"
}
}));
const navBodyStyle = makeStyles((theme) => ({
root: {
flexGrow: 1,
top: "0px",
position: "absolute",
width: "100%",
height: "100vh",
textAlign: "center",
background: "white",
zIndex: "9999",
height: "100%",
overflowY: "auto"
},
menuButton: {
marginRight: theme.spacing(2),
color: "purple"
},
title: {
flexGrow: 1,
textAlign: "center",
color: "black"
}
}));
const gridClassStyle = makeStyles((theme) => ({
root: {
zIndex: "100",
flexGrow: 1,
position: "fixed",
top: "0px",
background: "white",
flexWrap: "nowrap",
boxShadow: "5px 10px 18px #888888"
}
}));
const PrivacyPolicy = () => {
const navBody = navBodyStyle();
const navScroll = navScrollStyle();
const gridClass = gridClassStyle();
const NavPart = () => (
<Grid className={gridClass.root} container spacing={3}>
<BackButton />
<NameHeader name="PrivacyPolicy" /> {/* <-- Even here only name is changed */}
<AccountIcon />
</Grid>
);
return (
<div className={navBody.root}>
{NavPart()}
<div className={navScroll.root}>
<h2>This is Privacy Policy Section</h2> {/* And body part */}
</div>
</div>
);
};
export default PrivacyPolicy;
This is Privacy Policy page
In this manner, there are certain pages which has similar structure, except the changes in NameHeader and body part.
What I've tried is created new component and written all the common code in it, but, NavPart() was not working hence, the page was blank.
As you can see, styles and rest of structure remains same so what is the best solution to optimize it.
What my intention is to optimize the code, so no repetition of code is required
Please look at project here: https://codesandbox.io/s/react-material-forked-71op5

One of the easiest way is to create a so call "layout component" to contain all the common parts of the pages. For example your layout component may look like below:
Layout = (props)=>{
const navBody = navBodyStyle();
const navScroll = navScrollStyle();
const gridClass = gridClassStyle();
const NavPart = () => (
<Grid className={gridClass.root} container spacing={3}>
<BackButton />
<NameHeader name={props.name} />
<AccountIcon />
</Grid>
);
return (
<div className={navBody.root}>
{NavPart()}
<div className={navScroll.root}>
<h2>{props.title}</h2>
{props.children}
</div>
</div>
);
}
When you write the policy page, you may use like this:
const PrivacyPolicy = () => {
return (
<Layout name="PrivacyPolicy" title="This is Privacy Policy Section">
{/* And body part */}
</Layout>
);
};

Related

react did not render all rows and just rendered one object and reapeated

it should populate all rows to the table (the rows are from from the api is an array of objects) currently the issue is only render that last object of the array and I have no idea why it keeps on repeating , as you can see on the screenshot it only loads 1 object and then repeats that is why all the rows have the same value.
By the way the rows or the data from the api is an array of objects /
Maybe someone has an idea on how we can address this issue. Thanks.
#rows from the api result from the console log this is the rows that is been feed to the grid
#react code
export const StyledDataGrid = styled(DataGrid)`
.MuiDataGrid-row: nth-of-type(odd) {
background: #E3E0E0
}
.MuiDataGrid-cell {
border-right: 1px solid #C4C4C4;
}
.MuiDataGrid-columnHeader {
border-right: 1px solid #C4C4C4;
}
.MuiDataGrid-columnSeparator--sideRight {
display: none
}
.MuiDataGrid-columnHeaderTitleContainer {
justify-content: space-between;
}
.MuiDataGrid-iconButtonContainer {
visibility: visible;
width: auto;
}
`;
const PortfolioPage: FC = () => {
const router = useRouter();
const dispatch = useAppDispatch();
const { isPending, isError, isSuccess, grid, isSaveSuccess } = useAppSelector(
(state) => state.region
);
const [snackbarOpen, setSnackbarOpen] = useState<boolean>(false);
const [selectedRow, setSelectedRow] = useState<IRegional | null>(null)
const rows = grid ? grid.items : [];
console.log('rows' , rows)
const fetchGridItems = () => {
const payload: IPageListApiRequestPayload = {
accountId: 1,
sortKey: JSON.stringify([]),
sortOrder: JSON.stringify([]),
page: 1,
pageSize: 100,
searchString: '',
};
dispatch(getRegionGrid(payload));
}
useEffect(() => {
// Save success
if (isSaveSuccess) {
setSnackbarOpen(true);
fetchGridItems();
}
}, [isSaveSuccess])
useEffect(() => {
if (router.isReady) {
fetchGridItems();
}
}, [router.isReady]);
const renderList = (data: IEmail) => (
<div style={{display: 'block'}}>
<div>Full Name: {data.firstName} {data.lastName}</div>
<div>Email Address: {data.emailAddress}</div>
</div>
)
const columns: GridColDef[] = [
{
field: "associateDirectorofConstructionOps",
headerName: "Associate Director of Construction Ops",
minWidth: 300,
flex: 0.16,
disableColumnMenu: true,
renderCell: (params: GridRenderCellParams<string>) => (
<>
{
params.row.associateDirectorofConstructionOps ? params.row.associateDirectorofConstructionOps.map((prop: IEmail) => renderList(prop))
: null
}
</>
),
},
];
const fixedColumnLeft: GridColDef[] = [
{
field: "regionName",
headerName: "Region Division",
flex: 0.08,
minWidth: 100,
disableColumnMenu: true,
},
{
field: "subRegionName",
headerName: "Sub-Region",
flex: 0.15,
minWidth: 50,
disableColumnMenu: true,
},
{
field: "marketName",
headerName: "Market",
flex: 0.08,
minWidth: 50,
disableColumnMenu: true,
},
];
const fixedColumnRight: GridColDef[] = [
{
field: "action",
disableColumnMenu: true,
sortable: false,
renderHeader: () => <></>,
renderCell: (params: GridRenderCellParams<string>) => (
<div
style={{
color: "rgb(110 110 110)",
display: "flex",
justifyContent: "space-between",
}}
>
<EditIcon onClick={() => handleClickOpen(params)} />
</div>
),
},
];
const [open, setOpen] = React.useState<boolean>(false);
const handleClickOpen = (data: any) => {
setSelectedRow(data.row);
setOpen(true);
};
const handleClose = () => {
setOpen(false);
};
return (
<Box sx={{ height: "100vh", background: "#EEEAEA" }}>
<Snackbar
open={snackbarOpen}
autoHideDuration={3000}
onClose={() => setSnackbarOpen(false)}>
<Alert onClose={() => setSnackbarOpen(false)} severity="success" sx={{ width: '100%' }}>
Successfully saved!
</Alert>
</Snackbar>
<EditProperties open={open} handleClose={handleClose} selectedRow={selectedRow} />
<DashboardWrapper seoProps={{
title: "PIM | Regions",
}}
title="Properties"
mainClass="properties-page">
{isError ? <div>Error Loading Regions!</div> : ""}
{isPending ? <>Loading Regions...</> : ""}
{isSuccess ? (
<>
<div
style={{
display: "flex",
justifyContent: "space-between",
width: "636px",
height: "56px",
background: "rgba(37, 36, 41, 0.9)",
padding: "8px 16px 8px 8px",
borderBottomRightRadius: "30px",
}}
>
<Input
size="small"
style={{
width: "461px",
height: "40px",
background: "#FFFFFF",
borderRadius: "4px",
outline: "none",
}}
placeholder="Search by typing property name or address"
startAdornment={
<InputAdornment position="start">
<SearchIcon />
</InputAdornment>
}
/>
<Button
variant="contained"
style={{ textTransform: "capitalize" }}
>
Search
</Button>
<div
style={{
display: "flex",
color: "#FFFFFF",
flexDirection: "column",
justifyContent: "space-between",
alignItems: "center",
marginRight: "10px",
}}
>
<TuneIcon style={{ fontSize: "32px" }} />
<span style={{ fontSize: "10px", marginTop: "-5px" }}>
Filters
</span>
</div>
</div>
<TableContainer component={Paper} style={{ marginTop: "24px" }}>
<div
style={{
borderBottom: "1px solid #C4C4C4",
padding: "16px",
display: "flex",
justifyContent: "space-between",
background: "#FFFFFF",
height: "72px",
}}
>
<label
style={{
fontWeight: "600",
fontSize: "24px",
color: "#252429",
alignSelf: "center",
}}
>
{" "}
Regions{" "}
</label>
<div
style={{
alignSelf: "center",
color: "#C4C4C4",
display: "flex",
fontSize: "16px",
}}
>
<IosShareIcon style={{ marginRight: "14px" }} />
Export
</div>
</div>
{/* Table container */}
<div style={{position: "relative", display: 'flex', justifyContent: 'space-between'}}>
{/* Left table */}
<Box
sx={{ boxShadow: 5 }}
style={{
width: "20%",
zIndex: 99,
overflow: "hidden",
background: "#FFFFFF",
}}
>
<StyledDataGrid
autoHeight
getRowId={(row) => row.accountId}
hideFooterPagination={true}
components={{
ColumnSortedAscendingIcon: UnfoldMoreIcon,
ColumnSortedDescendingIcon: UnfoldMoreIcon,
}}
rows={rows}
columns={fixedColumnLeft}
disableSelectionOnClick
experimentalFeatures={{ newEditingApi: true }}
/>
</Box>
{/* Center table */}
<div style={{overflow: 'hidden', width: '70%'}}>
<div style={{ width: '2000px', margin: 'auto', overflow: "hidden"}} >
<StyledDataGrid
autoHeight
getRowId={(row) => row.accountId}
components={{
ColumnSortedAscendingIcon: UnfoldMoreIcon,
ColumnSortedDescendingIcon: UnfoldMoreIcon,
}}
rows={rows}
columns={columns}
pageSize={100}
rowsPerPageOptions={[10, 20, 50, 100]}
disableSelectionOnClick
experimentalFeatures={{ newEditingApi: true }}
/>
</div>
</div>
{/* Right table */}
<Box
sx={{ boxShadow: 5 }}
style={{
width: "10%",
zIndex: 99,
overflow: "hidden",
background: "#FFFFFF",
}}
>
<StyledDataGrid
autoHeight
getRowId={(row) => row.accountId}
hideFooterPagination={true}
components={{
ColumnSortedAscendingIcon: UnfoldMoreIcon,
ColumnSortedDescendingIcon: UnfoldMoreIcon,
}}
rows={rows}
columns={fixedColumnRight}
disableSelectionOnClick
experimentalFeatures={{ newEditingApi: true }}
/>
</Box>
</div>
</TableContainer>
{/* <ActionButtonContainer
btnNameOne="Property"
btnNameTwo="Properties"
btnIconOne={<UploadFileIcon />}
btnIconTwo={<AddIcon />}
/> */}
</>
) : (
""
)}
</DashboardWrapper>
</Box>
Yes because of this
This line is the cause of all these problems
The DataGrid expects a unique key for every row in the table
so it's asking you where it can find that unique key
You're telling it that it can find it inside the accountId prop.
Which is not accurate because it has duplicates
Normally this should be id, but it's null everywhere in your case.
If the data source coming from your API has a property called "id", the MUI DataGrid is automatically going to use it if you didn't set the getRowId prop.

How do I trigger a function at the first index of a react-elastic-carousel?

I have a specific request here that is throwing me off. I'm using react-slider-carousel and when it first loads, it has padded about 45px from the left. Then on the next arrow click, it removes the padding (this is done and easy). However, it shouldn't add the padding-left until it reaches its first index. In other words, until there are no more items to the navigate back to. Once it hits the left-most item (index-0) then it adds the padding-left back so that it looks like the way it was initially loaded.
Here's an example functionality that I have right now. It all works except that first index event thing I explained
import React, { useState, useEffect } from "react";
import ReactDOM from "react-dom";
import Carousel, { consts } from "react-elastic-carousel";
import Item from "./Item";
import "./styles.css";
const breakPoints = [
{ width: 1, itemsToShow: 1 },
{ width: 550, itemsToShow: 2, itemsToScroll: 2 },
{ width: 768, itemsToShow: 3 },
{ width: 1200, itemsToShow: 4 }
];
const items = [1, 2, 3, 4, 5, 6, 7, 8];
function App() {
const [first, setFirst] = useState(true);
useEffect(() => {
setFirst(true);
}, []);
const addPadding = () => {
setFirst(true);
};
const removePadding = () => {
setFirst(false);
};
const renderArrows = ({ type, onClick, isEdge }) => {
const pointer =
type === consts.PREV ? (
<div
style={{
top: 5,
left: 0,
display: "flex",
height: "100%",
width: "100%",
alignItems: "center",
justifyContent: "center"
}}
onClick={addPadding}
>
<span role="img" aria-label="">
👈
</span>
</div>
) : (
<div
style={{
top: 5,
right: 0,
display: "flex",
height: "100%",
width: "100%",
alignItems: "center",
justifyContent: "center"
}}
onClick={removePadding}
>
<span role="img" aria-label="">
👉
</span>
</div>
);
return (
<button
onClick={onClick}
disabled={isEdge}
style={{
zIndex: 1010,
width: 55,
fill: "black",
cursor: "pointer",
display: "flex",
alignItems: "center",
justifyContent: "center",
transition: "all .8s ease-in-out !default"
}}
>
{pointer}
</button>
);
};
return (
<div className="App">
<div className="controls-wrapper">
<button onClick={removePadding}>Remove Padding</button>
<button onClick={addPadding}>Add Padding</button>
</div>
<hr className="seperator" />
<div className="carousel-wrapper" style={{ backgroundColor: "maroon" }}>
<div
style={{
paddingLeft: first ? 45 : 15,
paddingTop: 15,
paddingBottom: 15,
paddingRight: 15
}}
>
<Carousel
breakPoints={breakPoints}
renderArrow={renderArrows}
style={{ backgroundColor: "white" }}
>
{items.map((item) => (
<Item key={item}>{item}</Item>
))}
</Carousel>
</div>
</div>
</div>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
Here's a handy dandy code Sandbox if you need to play around with it. And thanks in advance guys
You could try to utilize react-elastic-carousel props, such as onNextStart and onPrevStart which could provide to previous or future items, based on that you could remove/add padding.
Solution:
remove click assignment on line:39 and line:56 for prev/next arrow div elements
add onNextStart and onPrevStart callbacks as props on <Carousel>
include some logic in each onNextStart and onPrevStart callback to check for index for the future item in order to drive logic for padding (add/remove padding).
Codesandbox example

Material UI dark mode and light mode using react

Instead of switch component I want to use Light Mode and Dark Mode button on Navbar.js and Publish website need to be green on light and change color on dark mode but it not changing
I want to use two button on Navbar instead switch component and publish button background should be green on light mode and change color on dark mode.
App.js
import './App.css';
import React, {useState} from 'react';
import Body from './Body';
import Sidebar from './Sidebar';
import { makeStyles, ThemeProvider } from '#material-ui/core/styles';
import { createMuiTheme, CssBaseline, Switch } from '#material-ui/core';
const useStyles = makeStyles((theme) => ({
root: {
width: "1440px",
display: "flex",
}
}));
function App() {
const classes = useStyles();
const [darkMode, setDarkMode] = useState(false);
const theme = createMuiTheme({
palette: {
type: darkMode ? "dark" : "light",
}
})
const handleDarkMode = () => {
setDarkMode(!darkMode);
}
return (
<ThemeProvider theme={theme}>
<CssBaseline>
<Switch onChange={handleDarkMode} value={darkMode} />
<div className={classes.root}>
<Sidebar />
<Body />
</div>
</CssBaseline>
</ThemeProvider>
);
}
export default App;
Sidebar.js
import React from 'react';
import { makeStyles } from '#material-ui/core/styles';
const useStyles = makeStyles((theme) => ({
root: {
width: "260px",
// border: "1px solid black"
}
}));
function Sidebar() {
const classes = useStyles();
return (
<div className={classes.root}>
<h1>Hi</h1>
</div>
)
}
export default Sidebar;
Body.js
import React from 'react';
import Navbar from './Navbar';
import { makeStyles } from '#material-ui/core/styles';
import Builder from './Builder';
const useStyles = makeStyles((theme) => ({
root: {
width: "1180px",
height: "100%",
padding: "15px",
// border: "1px solid black",
// backgroundColor: "#f4f5f7",
}
}));
function Body() {
const classes = useStyles();
return (
<div className={classes.root}>
<Navbar />
<Builder />
</div>
)
}
export default Body
Navbar.js
import React from 'react';
import { makeStyles } from '#material-ui/core/styles';
import Brightness4Icon from '#material-ui/icons/Brightness4';
import Brightness7Icon from '#material-ui/icons/Brightness7';
import Button from '#material-ui/core/Button';
import OpenInNewIcon from '#material-ui/icons/OpenInNew';
const useStyles = makeStyles((theme) => ({
root: {
display: "flex",
justifyContent: "space-between"
},
leftNav: {
justifyContent: "center",
alignItems: "center",
borderRadius: "12px",
},
lightMode:{
justifyContent: "center",
alignItems: "center",
border: "none",
fontSize: "15px",
padding: "10px",
borderRadius: "12px",
textTransform: "none",
},
darkMode:{
justifyContent: "center",
alignItems: "center",
border: "none",
fontSize: "15px",
padding: "10px",
borderRadius: "12px",
textTransform: "none",
},
rightNav: {
justifyContent: "center",
alignItems: "center",
marginTop: "10px",
},
preview:{
marginRight: "15px",
textDecoration: "none",
justifyContent: "center",
alignItems: "center",
fontSize: "13px",
"&:hover": {
textDecoration: "underline",
}
},
publish:{
marginLeft: "15px",
textDecoration: "none",
backgroundColor: "#02AA02",
color: "white",
padding: "12px",
paddingLeft: "18px",
paddingRight: "18px",
borderRadius: "18px",
fontSize: "13px",
},
lightClick: {
backgroundColor: "red",
},
icons: {
marginRight: "8px",
}
}));
function Navbar() {
const classes = useStyles();
return (
<div className={classes.root}>
<div className={classes.leftNav}>
<Button variant="text" color="default" className={classes.lightMode} onClick={classes.lightClick}>
<Brightness7Icon className={classes.icons} />
Light mode
</Button>
<Button variant="text" color="default" className={classes.darkMode} onClick={classes.darkClick}>
<Brightness4Icon className={classes.icons} />
Dark mode
</Button>
</div>
<div className={classes.rightNav}>
<a href="#" className={classes.preview}>
Preview in new tab
<OpenInNewIcon fontSize="small" style={{fontSize: "15px", marginLeft: "5px"}} />
</a>
<a href="#"className={classes.publish}>Publish Website</a>
</div>
</div>
)
}
export default Navbar
Builder.js
import React from 'react';
import { makeStyles } from '#material-ui/core/styles';
import { Grid, Paper, Tabs, Tab } from '#material-ui/core';
import DesktopMacIcon from '#material-ui/icons/DesktopMac';
import TabletMacIcon from '#material-ui/icons/TabletMac';
import PhoneIphoneIcon from '#material-ui/icons/PhoneIphone';
const useStyles = makeStyles((theme) => ({
/* hidden preview's nav tab on mobile devices */
previewTab: {
// [theme.breakpoints.up('sm')]: {
// display: 'flex',
// },
// display: 'none',
},
builder: {
width: '100px',
height: '100px',
color: "white",
display: 'inline'
},
webPreviewContainer: {
textAlign: 'center',
},
}));
const Builder = () => {
const classes = useStyles();
return (
<Grid container direction='row' justify='center' alignItems='flex-start' spacing={4}>
<Grid
container item xs={12} md={12} lg={10}
justify='center' direction='row'
spacing={2}>
<Grid
item xs={12}
justify='center'
className={classes.previewTab}>
<Paper style={{width: "100%", marginTop: "20px",}}>
<Tabs
indicatorColor='primary'
textColor='primary'
centered
variant="fullWidth"
>
<Tab icon={<DesktopMacIcon />} label='Desktop' />
<Tab icon={<TabletMacIcon />} label='Tablet' />
<Tab icon={<PhoneIphoneIcon />} label='Mobile' />
</Tabs>
</Paper>
</Grid>
</Grid>
</Grid>
);
};
export default Builder;

React - how to apply local storage for hook value

I use the react-range package for personal purposes of my project, the problem is that I cannot save the value when the page is refreshed, I tried to use the local storage but I could not
As you understand, I need to save the value using local storage, in addition, I will leave a link to mine on codesandbox link
SideBarBlurChange.jsx
import React, {useEffect, useState} from "react";
import {getTrackBackground, Range} from "react-range";
const STEP = 0.1;
const MIN = 0;
const MAX = 100;
export default function SideBarBlurChange(props) {
const [values, SetValues] = useState([20])
const SaveChanges = () => {
alert(values)
}
return (
<>
<div
style={{
display: "flex",
justifyContent: "center",
flexWrap: "wrap",
}}
>
<Range
values={values}
step={STEP}
min={MIN}
max={MAX}
onChange={(values) => SetValues(values)}
renderTrack={({ props, children }) => (
<div
onMouseDown={props.onMouseDown}
onTouchStart={props.onTouchStart}
style={{
...props.style,
height: "36px",
display: "flex",
width: "100%"
}}
>
<div
ref={props.ref}
style={{
height: "5px",
width: "100%",
borderRadius: "4px",
background: getTrackBackground({
values: values,
colors: ["#548BF4", "#ccc"],
min: MIN,
max: MAX
}),
alignSelf: "center"
}}
>
{children}
</div>
</div>
)}
renderThumb={({ props, isDragged }) => (
<div
{...props}
style={{
...props.style,
height: "42px",
width: "42px",
borderRadius: "4px",
backgroundColor: "#FFF",
display: "flex",
justifyContent: "center",
alignItems: "center",
boxShadow: "0px 2px 6px #AAA"
}}
>
<div
style={{
height: "16px",
width: "5px",
backgroundColor: isDragged ? "#548BF4" : "#CCC"
}}
/>
</div>
)}
/>
<output style={{ marginTop: "30px" }} id="output">
{values[0].toFixed(1)}
</output>
<button onClick={() => SaveChanges()}>Save</button>
</div>
</>
);
}
I think your main problem was that localStorage doesn't store anything besides strings. You're going to want to parseInt then check to make sure localStorage isn't null. Can you try this and see if it works?
const ls = parseInt(window.localStorage.getItem('values'));
const [values, SetValues] = useState(ls ? [ls] : [20]);
const SaveChanges = () => {
alert(values);
localStorage.setItem('values', values);
}

Material-UI styles: convert functional component to class component

So I try the following code to convert a functional component to the classical component, it kinda worked, no error but styles are not applied.
import { makeStyles } from '#material-ui/core/styles';
import { withStyles } from '#material-ui/core/styles';
const playtheMusic = () => {
pauseMusic();
};
const pausetheMusic = () => {
pauseMusic();
};
const useStyles = makeStyles(theme => ({
text: {
padding: 50
},
paper: {
paddingBottom: 50
},
list: {
marginBottom: theme.spacing(2)
},
subheader: {
backgroundColor: theme.palette.background.paper
},
appBar: {
top: 'auto',
bottom: 0,
backgroundColor: '#282828',
padding: '15px'
},
grow: {
flexGrow: 1
}
}));
class BottomAppBar extends React.Component {
// const classes = useStyles();
render() {
const { classes } = this.props;
return (
<div>
<AppBar position="fixed" className={classes.appBar}>
<div style={{ display: 'flex', alignItems: 'center', alignContent: 'center' }}>
<div>
<Typography style={{ fontSize: 15 }}> Stress Out </Typography>
<br />
<Typography style={{ fontSize: 12, color: '#B3B3B3' }}>
Twenty One Pilots
</Typography>
</div>
<div className={classes.grow} />
<div>
<IconButton style={{ color: 'white' }}>
<ShuffleIcon />
</IconButton>
<IconButton style={{ color: 'white' }}>
<SkipPreviousRoundedIcon style={{ fontSize: 30 }} />
</IconButton>
<IconButton onClick={pausetheMusic} style={{ color: 'white' }}>
<PauseCircleOutlineRoundedIcon style={{ fontSize: 46 }} />
<PlayCircleOutlineIcon style={{ fontSize: 46, display: 'none' }} />
</IconButton>
<IconButton style={{ color: 'white' }}>
<SkipNextRoundedIcon style={{ fontSize: 30 }} />
</IconButton>
<IconButton style={{ color: 'white' }}>
<RepeatIcon />
</IconButton>
</div>
<div className={classes.grow} />
<div>
<IconButton style={{ color: 'white' }}>
<VolumeUpIcon />
</IconButton>
</div>
</div>
</AppBar>
</div>
);
}
}
export default withStyles(useStyles)(BottomAppBar);
also, there is a problem with StackOverflow. it says "It looks like your post is mostly code; please add some more details". that's the reason I'm writing some unnecessary things XD
you can skip it.
Thanks for reading. have a good day <3
A common approach for material-ui component styling:
Classical
withStyles (High order function) + createStyles
Functional
useStyles (hooks) + makeStyles
In your code, you shall not use the hooks useStyles inside withStyle, hooks shouldn't be used inside any classical component,
Wrong here
export default withStyles(useStyles)(BottomAppBar);
Right example
import { withStyles, createStyles } from "#material-ui/core/styles";
const styles = theme => createStyles({
root: {
},
// ...
});
...
const { classes } = this.props;
...
export default withStyles(styles)(App);
Online sample for both classical component and functional component styling

Categories

Resources