How to add css style in react espically for MUI component - css

I just start to learning react, now I'm going to use css style and use it in className for customizing the Mui component. But it doesn't work. Here is the code in tsx
export default function NaviDispatcher(): JSX.Element {
const [value, setValue] = React.useState(0);
return (<Paper elevation={3} className='navigation'>
<BottomNavigation
showLabels
value={value}
onChange={(event, newValue) => {
setValue(newValue);
}}
className='navibar'
>
<BottomNavigationAction style={label} label="Box Management" />
<BottomNavigationAction style={label} label="Deliveries Management" />
<BottomNavigationAction style={label} label="Users Management" />
<BottomNavigationAction style={label} label="Deliverer Management" />
<BottomNavigationAction style={label} label="Create New Delivery" />
</BottomNavigation>
</Paper>);
}
Here is the code in css.
.navigation {
display: flex;
flex-direction: row;
background-color: black;
}
.navibar {
display: flex;
flex-direction: column;
position: fixed;
width: 100%;
}
When I check the element by F12, I didn't find any element named by navigation or navibar. Did I wrong when I add css style? Is there somethingelse I should do?

since you are using MUI, have you imported {makeStyles} from '#material-ui/core' in your css file?
in you tsx file you should do this:
xport default function NaviDispatcher(): JSX.Element {
const [value, setValue] = React.useState(0);
const classes = useStyles()
return (<Paper elevation={3} className={classes.navigation}>
<BottomNavigation
showLabels
value={value}
onChange={(event, newValue) => {
setValue(newValue);
}}
className={classes.navibar}
>
<BottomNavigationAction style={label} label="Box Management" />
<BottomNavigationAction style={label} label="Deliveries Management" />
<BottomNavigationAction style={label} label="Users Management" />
<BottomNavigationAction style={label} label="Deliverer Management" />
<BottomNavigationAction style={label} label="Create New Delivery" />
</BottomNavigation>
</Paper>);
}
import { makeStyles } from '#material-ui/core'
export default makeStyles((theme) => ({
.navigation {
display: flex;
flex-direction: row;
background-color: black;
}
.navibar {
display: flex;
flex-direction: column;
position: fixed;
width: 100%;
}
}
))

Related

Change the position of the buttons

I have a project, and in this project I have an interface that contains several fields in addition to two buttons, the first is “Create” and the second is “cancel”, and as it is clear in the picture the two buttons at the end, but I want the two buttons to be in the area in which there is writing in color red
How can I do that?
And the file for the interface is large, so I only put the method of writing the two buttons
main.js:
<div className="p-16 sm:p-24 max-w-2xl ">
<div className={tabValue !== 0 ? "hidden" : ""}>
<ShippingTab />
</div>
</div>
shipping.js:
import React, { useState } from "react";
import InputAdornment from "#material-ui/core/InputAdornment";
import TextField from "#material-ui/core/TextField";
import Grid from "#material-ui/core/Grid";
import "date-fns";
import DateFnsUtils from "#date-io/date-fns";
import {
KeyboardDatePicker,
MuiPickersUtilsProvider,
DatePicker,
} from "#material-ui/pickers";
import { makeStyles } from "#material-ui/core/styles";
import Button from "#material-ui/core/Button";
import CloudUploadIcon from "#material-ui/icons/CloudUpload";
import { addInvoice } from "../../../store/invoiceSlice";
import { motion } from "framer-motion";
import { useDispatch } from "react-redux";
import "react-datepicker/dist/react-datepicker.css";
import Slide from "#material-ui/core/Slide";
import { useSnackbar } from "notistack";
const useStyles = makeStyles((theme) => ({
root: {
"& > *": {
margin: theme.spacing(1),
},
},
input: {
display: "none",
},
button: {
margin: theme.spacing(1),
// padding: theme.spacing(4),
},
}));
function ShippingTab(props) {
const dispatch = useDispatch();
const classes = useStyles();
const [issueDate, setIssueDate] = useState(new Date());
const [dueDate, setDueDate] = useState(new Date());
const [netAmount, setNetAmount] = useState("");
const [taxNumber, setTaxNumber] = useState("");
const [grossAmount, setGrossAmount] = useState("");
const [file, setFile] = useState(null);
const { enqueueSnackbar, closeSnackbar } = useSnackbar();
const handleUploadPDFFileMessageClick = () => {
enqueueSnackbar(
"PDF file has been uploaded successfully",
{ variant: "success" },
{
anchorOrigin: {
vertical: "top",
horizontal: "right",
},
},
{ TransitionComponent: Slide }
);
};
const handleCreateInvoiceMessageClick = () => {
enqueueSnackbar(
"Invoice created successfully",
{ variant: "success" },
{
anchorOrigin: {
vertical: "top",
horizontal: "right",
},
},
{ TransitionComponent: Slide }
);
};
const fileSelectedHandler = (event) => {
console.log(event.target.files[0]);
const file = event.target.files[0];
if (event.target && file) {
// formData.append("invoice", file);
setFile(file);
}
};
const uploadHandler = (event) => {
const formData = new FormData();
formData.append("grossAmount", grossAmount);
formData.append("taxNumber", taxNumber);
formData.append("netAmount", netAmount);
formData.append("issueDate", issueDate);
formData.append("dueDate", dueDate);
formData.append("invoice", file);
console.log(
" invoice grossAmount,taxNumber,netAmount,",
file,
grossAmount,
taxNumber,
netAmount
);
console.log("dueDate,issueDate: ", dueDate, issueDate);
// call api
dispatch(addInvoice(formData));
};
const handleissueDateChange = (date) => {
setIssueDate(date);
console.log("date issssssssss: ", date);
console.log("date issssssssss: ", issueDate);
};
const handleDueDateChange = (date) => {
setDueDate(date);
};
const handleNetAmountChange = (event) => {
setNetAmount(event.target.value);
};
const handleTaxAmountChange = (event) => {
setTaxNumber(event.target.value);
};
const handleGrossAmountChange = (event) => {
setGrossAmount(event.target.value);
};
return (
<>
<MuiPickersUtilsProvider utils={DateFnsUtils}>
<div className="flex -mx-4">
<KeyboardDatePicker
inputVariant="outlined"
className="mt-8 mb-16"
margin="normal"
id="date-picker-dialog"
label="issue Date"
format="MM/dd/yyyy"
KeyboardButtonProps={{
"aria-label": "change date",
}}
value={issueDate}
onChange={handleissueDateChange}
/>
<KeyboardDatePicker
inputVariant="outlined"
className="mt-8 mb-16 ml-6"
margin="normal"
id="date-picker-dialog"
label="Due Date"
format="MM/dd/yyyy"
KeyboardButtonProps={{
"aria-label": "change date",
}}
value={dueDate}
onChange={handleDueDateChange}
/>
</div>
</MuiPickersUtilsProvider>
<TextField
className="mt-8 mb-16"
label="Net Amount"
id="extraShippingFee"
variant="outlined"
InputProps={{
startAdornment: <InputAdornment position="start">$</InputAdornment>,
}}
value={netAmount}
onChange={handleNetAmountChange}
fullWidth
/>
<TextField
className="mt-8 mb-16"
label="Tax Number"
id="extraShippingFee"
variant="outlined"
InputProps={{
startAdornment: <InputAdornment position="start">$</InputAdornment>,
}}
value={taxNumber}
onChange={handleTaxAmountChange}
fullWidth
/>
<TextField
className="mt-8 mb-16"
label="Gross Amount"
id="extraShippingFee"
variant="outlined"
InputProps={{
startAdornment: <InputAdornment position="start">$</InputAdornment>,
}}
value={grossAmount}
onChange={handleGrossAmountChange}
fullWidth
/>
<div className={classes.root}>
<input
accept="application/pdf"
className={classes.input}
id="contained-button-file"
// multiple
type="file"
onChange={fileSelectedHandler}
/>
<label htmlFor="contained-button-file">
<Button
variant="contained"
color="primary"
size="large"
component="span"
className={classes.button}
startIcon={<CloudUploadIcon />}
>
{/* <Button variant="contained" color="primary" component="span"> */}{" "}
Upload
</Button>
{/* </Button> */}
</label>
</div>
<motion.div
initial={{ opacity: 0, x: 20 }}
animate={{ opacity: 1, x: 0, transition: { delay: 0.3 } }}
>
<Grid
container
direction="row-reverse"
justifyContent="flex-start"
alignItems="flex-end"
>
<Grid item>
<Button
className="whitespace-nowrap mx-4"
variant="contained"
color="secondary"
// onClick={handleRemoveProduct}
>
Cancel
</Button>
</Grid>
<Grid item>
<Button
className="whitespace-nowrap mx-4"
variant="contained"
color="secondary"
// disabled={_.isEmpty(dirtyFields) || !isValid}
onClick={(ev) => {
uploadHandler();
ev.stopPropagation();
handleCreateInvoiceMessageClick(ev);
}}
>
Create
</Button>
</Grid>
</Grid>
</motion.div>
</>
);
}
export default ShippingTab;
You can align the two buttons to the left bottom using flex and height: 100%.
All the parents of the two buttons from the motion.div upwards including html and body need to have 100% height.
The grid that contains the buttons and motion.div need to have flex-grow:1 so that they occupy all the free space in their respective container.
html,
body {
height: 100%;
}
div.container {
height: 100%;
display: flex;
flex-direction: column;
}
section.red {
background: red;
padding: 5rem 0
}
section.blue {
background: blue;
padding: 5rem 0
}
section.green {
background: green;
flex-grow: 1;
display: flex;
}
section.green>div {
height: 100%;
width: 100%;
display: flex;
flex-direction: column;
}
section.left {
flex-grow: 1;
display: flex;
justify-content: flex-end;
align-items: flex-end;
}
button {
padding: 1rem 2rem;
}
<div class="container">
<section class="red"></section>
<section class="blue"></section>
<section class="green">
<div>
<section class="right">
<button>Right</button>
</section>
<section class="left">
<button>One</button>
<button>TWO</button>
</section>
</div>
</section>
</div>
If ShippingTab has too many parents, it is hard to set 100% height on all of its parent. In that case, you may absolutely postion it either in the body or in its nearest relative container that has / can have 100% height.
The parent is a flex element, so try margin-top: auto; on the children (buttons or container thereof)

How to remove styling from Link of react router with styled-components

I'm using styled-components but in a different file. I've searched for this question and found many answers, but I'm still confused about how to apply it in my code version. So, sorry in advance if it will be repetitive.
File Main.jsx :
import { BrowserRouter as Router, Switch, Route, Link } from "react-router-dom";
function Main() {
return (
<>
<Router>
<MainComponent>
<Menu>
<Link to="/crypto">
<HyperLink>Crypto</HyperLink>
</Link>
<Link to="/marketplace">
<HyperLink>Market Place</HyperLink>
</Link>
</Menu>
<Switch>
<Route path="/crypto" component={Crypto} />
<Route path="/marketplace" component={MarketPlace} />
</Switch>
</MainComponent>
</Router>
</>
);
}
File MainElements.jsx:
import styled from "styled-components";
export const MainComponent = styled.div`
width: 100%;
height: 100vh;
background-color: #1e2258;
`;
export const Menu = styled.div`
display: flex;
width: 80%;
margin: auto;
height: 10vh;
color: #fff;
border: 1px solid white;
align-items: center;
`;
export const HyperLink = styled.p`
text-decoration: none;
&:focus,
&:hover,
&:visited,
&:link,
&:active {
text-decoration: none;
}
`;
Can try example from react-router docs https://reactrouter.com/web/api/Link/component-reactcomponent
Just use a tag instead of p for link.
const FancyLink = React.forwardRef((props, ref) => (
<HyperLink ref={ref} {...props}>{props.children}</HyperLink>
))
<Link to="/" component={FancyLink} />
const CustomLink = ({ ...props }) => <Link component={FancyLink} {...props} />

How to styled image in next.js

import styled from 'styled-components'
import Image from 'next/image'
function Selection() {
const NavSelection = styled.nav`
background-color: rgb(240, 240, 240);
margin-bottom: 50px;
`
const UlFlex = styled.ul`
display: flex;
justify-content: space-around;
li{
list-style: none;
}
`
return (
<div>
<NavSelection>
<Image
src="/logo-crazy-monkey-hd-png-download-800x11312396344-pngfind-crazy-hd-png-840_886.png"
width={100}
height={100}
/>
</NavSelection>
</div >
)
}
export default Selection
Questions:
How can I style the image to apply postion:abloute to the image component?
What to apply more stylish in image component (this image is logo, not a photo)?
So how can I use styleCompnent or className to position the logo? I tried both, but it did not work.
You can add style={{ STYLE HERE } in your component to custom it
<Image
src="/logo-crazy-monkey-hd-png-download-800x11312396344-pngfind-crazy-hd-png-840_886.png"
width={100}
height={100}
style={{ position: "absolute"}}
/>

How to show less number of pages on mobile view in Pagination?

Problem
Need to show less number of pages in mobile view so that it can be aligned with heading (My Orders) in the same line.
Library
material-ui/pagination
Progress
Able to remove Next and Previous content in the mobile view but neither able to find any out-of-the-box prop(s) nor any CSS to reduce number of pages in mobile view
Web view
Mobile View
Code
CSS
#media (min-width: 501px) {
.MuiPagination-root {
.MuiPagination-ul {
flex-wrap: nowrap;
li {
&:first-child {
flex-basis: 100%;
display: flex;
justify-content: flex-start;
align-items: center;
> button::before {
margin-right: 10px;
content: "Previous ";
}
}
&:last-child {
flex-basis: 100%;
display: flex;
justify-content: flex-end;
align-items: center;
> button::after {
margin-left: 10px;
margin-right: 20px;
content: " Next";
}
}
}
}
}
Custom Component
import React, { useState } from "react";
import PropTypes from "prop-types";
import Pagination from '#material-ui/lab/Pagination';
export const CustomPagination = ({ onChange, totalRecords, currentPage, className, shape }) => {
return (
<Pagination
count={totalRecords}
shape={shape}
className={className}
onChange={onChange}
page={currentPage}
/>
)
};
CustomPagination.propTypes = {
paginationLength: PropTypes.number,
selectPage: PropTypes.func,
activePage: PropTypes.number,
};
One of the solutions I came up with is wrapping the component pagination inside a Box then changing its size depending on the view :
export function Test() {
return;
<>
<Box sx={{ display: { xs: "none", md: "block" } }}>
<Pagination
/>
</Box>
<Box sx={{ display: { xs: "block", md: "none" } }}>
<Pagination
size="small"
/>
</Box>
</>;
}
</Box>

Generating a grid-container style when mapping through an array

Summary
I have the following chart image (react-vis):
My React code (below) is creating this with a map through an array. How should I modify the code so the charts go across the page and are contained in some kind of fluid wrapper like this:
What have I looked at/tried?
I have basic understanding of HTML and CSS but would not know how to approach this kind of task and modify the code.
Would I need to use something like this and integrate with the code above?
<div class="grid-container">
<div className="grid-item">1</div>
<div className="grid-item">2</div>
<div className="grid-item">3</div>
<div className="grid-item">4</div>
</div>
I would like to understand an effective way to do this please using CSS, bootstrap or whatever would be considered best practice.
Code:
MyComp.js
import React, { useState, useEffect } from "react"
import Example from "./plotBar.js"
function getJson() {
return fetch("http://secstat.info/testthechartdata3.json")
.then(response => response.json())
.catch(error => {
console.error(error)
})
}
const MyComp = () => {
const [list, setList] = useState([])
useEffect(() => {
getJson().then(list => setList(list))
}, [])
return (
<div>
{list.map((data, index) => (
<Example
key={index}
data={data.map(({ id, count }) => ({
x: id,
y: count,
}))}
/>
))}
</div>
)
}
export default MyComp
plotBar.js
import React from "react"
import {
XYPlot,
XAxis,
YAxis,
VerticalGridLines,
HorizontalGridLines,
VerticalBarSeries,
} from "react-vis"
export default function Example({ data }) {
return (
<XYPlot margin={{ bottom: 70 }} xType="ordinal" width={300} height={300}>
<VerticalGridLines />
<HorizontalGridLines />
<XAxis tickLabelAngle={-45} />
<YAxis />
<VerticalBarSeries data={data} />
</XYPlot>
)
}
The data looks like this:
URL for JSON
http://secstat.info/testthechartdata3.json
You should read about flex and flex-flow, after that it just applying minor styling, this is CSS-in-JS example:
const Item = styled(Example)``;
const Container = styled.div`
display: flex;
flex-flow: row wrap;
background: lightgray;
padding: 0.5rem;
${Item} {
margin: 0.5rem;
padding: 1rem;
background: white;
}
`;
const Item = styled(Example)``;
const Container = styled.div`
display: flex;
flex-flow: row wrap;
background: lightgray;
padding: 0.5rem;
${Item} {
margin: 0.5rem;
padding: 1rem;
background: white;
}
`;
export default function Example({ data, className }) {
return (
<XYPlot className={className} xType="ordinal" width={200} height={200}>
<VerticalGridLines />
<HorizontalGridLines />
<XAxis tickLabelAngle={-45} />
<YAxis />
<VerticalBarSeries data={data} />
</XYPlot>
);
}
const list = // fetch on mount
const MyComp = () => {
return (
<Container>
{list.map((data, index) => (
<Item
key={index}
data={data.map(({ id, count }) => ({
x: id,
y: count,
}))}
/>
))}
</Container>
);
};

Resources