How to create a dashboard grid with material-ui for react? - javascript

I have the following react code and the thing that I want is to create a dashboard, but before I need to create a Grid for it.
I have the following code (using the material-ui grid system "https://material-ui.com/components/grid/")
import React from 'react';
import { makeStyles } from '#material-ui/core/styles';
import Paper from '#material-ui/core/Paper';
import Grid from '#material-ui/core/Grid';
const useStyles = makeStyles((theme) => ({
root: {
flexGrow: 1,
},
paper: {
padding: theme.spacing(2),
textAlign: 'center',
color: theme.palette.text.secondary,
},
}));
function App() {
const classes = useStyles();
return (
<div>
<Grid container spacing={2}>
<Grid alignItems='baseline' item xs={3}>
<Paper className={`${classes.paper}`}>xs=3</Paper>
</Grid>
<Grid item xs={9}>
<Paper className={classes.paper}>xs=6</Paper>
<Paper className={`${classes.paper} ${styles.content}`} height="100%">xs=6</Paper>
</Grid>
</Grid>
</div>
);
}
export default App;
The result I want is the one from the 1 image, however the result that I have so far is the one from the second image, I am pretty sure that something is wrong with my code, I am not react expert.
Any help here will be aprecciated

Related

How to map data to react component?

I have data returned from the backend now i am trying to map it to react component which is throwing an error Cannot read property of null what is correct way to print keys in the div or card , i have also attached the data
index.js
import React, { Component } from 'react';
import './app.css';
import ReactImage from './react.png';
import AppBar from '#mui/material/AppBar';
import Box from '#mui/material/Box';
import Toolbar from '#mui/material/Toolbar';
import Typography from '#mui/material/Typography';
import IconButton from '#mui/material/IconButton';
import MenuIcon from '#mui/icons-material/Menu';
import Paper from '#mui/material/Paper';
import Grid from '#mui/material/Grid';
import { styled } from '#mui/material/styles';
export default class JOB_DESC extends Component {
state = { data: null };
async componentDidMount() {
try {
const response = await fetch('/api/getUsername');
const data = await response.json();
this.setState({ data: data });
} catch (e) {
if (e.name != "AbortError") this.setState({ error: e.message });
}
}
render() {
const data = this.state.data;
console.log("DATA", data);
return (
<Box sx={{ flexGrow: 1 }}>
<AppBar position="static">
<Toolbar>
<IconButton
size="large"
edge="start"
color="inherit"
aria-label="menu"
sx={{ mr: 2 }} >
<MenuIcon />
</IconButton>
<Typography variant="h6" component="div" sx={{ flexGrow: 1 }}>
Job.com
</Typography>
</Toolbar>
</AppBar>
<div style={{ padding: 20 }}>
<Grid container spacing={4}>
<Grid item xs={12}>
<p>`{data["User Account"]}`</p>
<p>`{data["User Location"]}`</p>
<p> `{data["Company Name"]}`</p>
</Grid>
</Grid>
</div>
</Box>
);
}
}
data
{ ‘User Account': Admin’,
‘User Location': ': New York, NY',
'Company Name': ': Millennium’ }
It looks like by the time your component gets rendered, data will still be null as you've set it to null. So attempting to index null will give you Cannot read property of null.
What you'd want to do is wrap your component with a condition to check if data exists by the time it renders.
{ data && (
<div style={{ padding: 20 }}>
<Grid container spacing={4}>
<Grid item xs={12}>
<p>`{data["User Account"]}`</p>
<p>`{data["User Location"]}`</p>
<p> `{data["Company Name"]}`</p>
</Grid>
</Grid>
</div>
)}

issues with funnel of highcharts

I'm trying to create a funnel chart using highcharts-react-official but I get an error that says:
**Uncaught TypeError: Cannot read property 'noop' of undefined
it occurs in funnel.js inside highchart's modules. and makes browers stuck in debugger mode. Any help would be appreciated.
thanks in advance
this is my code:
import React from 'react';
import { Grid, Typography } from '#material-ui/core';
import TextCountComp from '../../../../shared/components/textCount/TextCountComp';
import useStyles from './ChartAnalyticsCompStyle';
import Highcharts from "highcharts/highstock";
import funnel from "highcharts/modules/funnel.js";
import HighchartsReact from "highcharts-react-official";
funnel(Highcharts);
const options = {
series: [
{
type: "funnel",
data: [1, 2, 3]
}
]
}
const ChartAnalyticsComp = () => {
const classes = useStyles();
return (
<Grid container className={classes.root}>
<Grid item xs={2} className={classes.grid}>
<TextCountComp className={classes.box} align="center" headText="Total" value="$0" />
</Grid>
<Grid item xs>
{/* chart goes here */}
Chart
<HighchartsReact highcharts={Highcharts} options={options} />
</Grid>
<Grid container item xs direction="column">
{/* texts goes here just use <Typography> component for each line of text */}
<Typography>Text 1</Typography>
<Typography>Text 2</Typography>
....
</Grid>
</Grid>
);
};
export default ChartAnalyticsComp;
this is the TextCountComp that is used above.
import React from 'react';
import { Box, Typography, TypographyTypeMap } from '#material-ui/core';
interface PropType {
headText: string;
value: string | number;
color?: TypographyTypeMap['props']['color'];
align?: TypographyTypeMap['props']['align'];
border?: boolean;
className?: string;
}
const TextCountComp = (
{
headText, value, color, border, align, className,
}: PropType,
) => (
<Box border={+border!} className={className}>
<Typography variant="body1" color={color}>{headText}</Typography>
<Typography align={align} variant="body1" color="secondary">{value}</Typography>
</Box>
);
TextCountComp.defaultProps = {
color: 'primary',
border: true,
align: 'center',
className: undefined,
};
export default TextCountComp;

How to change size of tabs components in Materials-UI?

I am working on a simple app to display heart rate, blood glucose levels and several other measurements. I am working in React and Redux, and using Materials-UI for UI.
To display these two numbers, I am creating a component that will be on each half of the screen. Under each number, I will have a set of tabs to switch within views of the component.
I want to resize the tabs to be the correct size, but it is too large currently and takes up too much space. How can I resize the tabs to be smaller. I have the code below for creating tabs and have read through this and this but am unsure on how to do this.
I attempted use withStyles(styles) as shown below, but it doesn't work properly.
import React from 'react';
import { makeStyles } from '#material-ui/core/styles';
import Paper from '#material-ui/core/Paper';
import Tabs from '#material-ui/core/Tabs';
import Tab from '#material-ui/core/Tab';
import { withStyles } from '#material-ui/core/styles';
import Grid from '#material-ui/core/Grid';
const BottomTab = ({}) => (
<Grid item direction="column" alignItems="center" justify="center">
<Tabs
value={0}
indicatorColor="primary"
textColor="primary"
variant="fullWidth"
>
<Tab label="Current" />
<Tab label="Set New" />
<Tab label="Alarm" />
</Tabs>
</Grid>
);
const styles = {
tab: {
width: '10', // a number of your choice
}
};
export default withStyles(styles)(BottomTab);
and the following code block is where I call the BottomTab.
interface Props {
labelId: string,
value: number
}
const Knob = ({labelId, value}: Props) => (
<Grid item container direction="row" alignItems="center" justify="center">
<Grid item xs>
<ValueDisplay labelId={labelId} value={value} />
</Grid>
<Grid item container direction="column" alignItems="center" justify="space-evenly">
<BottomTab />
</Grid>
</Grid>
)
export default Knob
In BottomTab, you should create a class in with a property minWidth: <your tab size>, and then use this class to style Tab component, like this:
const useStyles = makeStyles((theme) => ({
...
tabs: {
'& button': {
minWidth: 50
}
}
}));
const BottomTab = ({}) => {
const classes = useStyles()
return (
<Grid item direction="column" alignItems="center" justify="center">
<Tabs
value={0}
indicatorColor="primary"
textColor="primary"
variant="fullWidth"
className={classes.tabs}
>
<Tab label="Current" />
<Tab label="Set New" />
<Tab label="Alarm" />
</Tabs>
</Grid>
)
};
Have you tried adding component to its own grid and then changing the size.
Might not work, but worth a try.
Note: sorry for answering, but I can't comment yet due to reputation restriction.

How do I center TabPanel in React material UI?

I am trying to create a list of articles with switching to a list of other entities in React + material UI. But I faced some problems, namely, I can't center Card, which displays an article in the way, that will correspond to centered Tabs. So, I get something like this:
Can anyone help me to make it to look symmetric?
I want the Card to be centered in the same way, the Tabs are.
TabsMenu.js, which itself is displayed:
import React from "react";
import {makeStyles} from "#material-ui/core/styles";
import Paper from "#material-ui/core/Paper";
import Tabs from "#material-ui/core/Tabs";
import Tab from "#material-ui/core/Tab";
import Box from "#material-ui/core/Box";
import Typography from "#material-ui/core/Typography";
import * as PropTypes from "prop-types";
import ArticlesList from "./ArticlesList";
function TabPanel(props) {
const {children, value, index, ...other} = props;
return (
<div
role="tabpanel"
hidden={value !== index}
id={`simple-tab-${index}`}
aria-labelledby={`simple-tab-${index}`}
{...other}
>
{value === index && (
<Box p={3}>
<Typography>{children}</Typography>
</Box>
)}
</div>
);
}
TabPanel.propTypes = {
children: PropTypes.node,
index: PropTypes.any.isRequired,
value: PropTypes.any.isRequired,
};
const useStyles = makeStyles({
root: {
flexGrow: 1,
},
tabpanel: {
marginLeft: "auto"
}
});
function a11yProps(index) {
return {
id: `simple-tab-${index}`,
'aria-controls': `simple-tabpanel-${index}`,
};
}
export default function CenteredTabs(props) {
const classes = useStyles();
const [value, setValue] = React.useState(0);
const handleChange = (event, newValue) => {
setValue(newValue);
}
return (
<Paper className={classes.root}>
<article>
<Tabs
value={value}
onChange={handleChange}
indicatorColor="primary"
textColor="primary"
centered
>
<Tab label="Articles" {...a11yProps(0)}/>
<Tab label="News" {...a11yProps(1)}/>
<Tab label="Authors" {...a11yProps(2)}/>
</Tabs>
<TabPanel value={value} index={0} className={classes.tabpanel}>
<ArticlesList articles={[{
imageSrc: "https://frontendmasters.com/static-assets/learn/og-learning-path-react.jpg",
authorImageSrc: "https://lh5.googleusercontent.com/--OlyHl449xI/AAAAAAAAAAI/AAAAAAAAAAA/ACevoQNk7ZZElQ_vKIQT_6d4HZw_wN3Qxg/mo/photo.jpg?sz=64",
authorName: "Denis Ivanenko",
dateTime: "2017-02-14",
imageAlt: "Article Image",
title: "Test title",
subtitle: "Test subtitle"
}]}/>
</TabPanel>
<TabPanel value={value} index={1} className={classes.tabpanel}>
Item Two
</TabPanel>
<TabPanel value={value} index={2} className={classes.tabpanel}>
Item Three
</TabPanel>
</article>
</Paper>
);
}
ArticlesList.js, which is used in TabsMenu.js
import React from 'react';
import {makeStyles} from '#material-ui/core/styles';
import List from '#material-ui/core/List';
import ArticleCard from "./ArticleCard";
import Box from "#material-ui/core/Box";
import Grid from '#material-ui/core/Grid';
const useStyles = makeStyles((theme) => ({
root: {
width: '100%',
maxWidth: 360,
backgroundColor: theme.palette.background.paper,
},
}));
export default function ArticlesList(props) {
const classes = useStyles();
return (
<React.Fragment>
<div className={classes.root}>
<Grid container
spacing={0}
direction="column"
alignItems="center"
justify="center"
style={{minHeight: '100vh'}}>
<Grid item xs={12}>
<Box width={"150%"}>
<List component="nav" aria-label="secondary mailbox folders">
<ArticleCard title={"Introducing \"Dead Simple Python\"\n"}
text={"Ever spent three hours trying to find that bit of knowledge that everyone seemed to have but you?\n" +
"\n" +
"As a self-trained Python developer, I've sometimes found myself stuck in that knowledge crater, between tutorials far simpler than real life, and articles more advanced than I could comprehend. Even the documentation felt like a firehose of information, making it nearly impossible to find the one basic thing I needed to know.\n" +
"\n" +
"In this series, I'll be exploring a few of these topics, in a way that hopefully makes them dead simple!\n" +
"\n" +
"Intended Audience\n" +
"While programmers at all experience levels may find this series useful, I'm specifically targeting Python novices. I am assuming, however, that you have a very basic understanding of programming. The coding topics especially will be more focused on the Python way of doing things, not on the underlying generic concept.\n" +
"\n" +
"With that said, if you're an intermediate-level Python developer, you may still find it helpful to follow along with the series. Although I've been working with Python for nearly eight years, some of these topics didn't really \"click\" for me until recent years. These are the explanations I wish I'd had!\n" +
"\n" +
"What You Won't Find Here\n" +
"All of the topics I'm discussing here go much, much deeper. However, I don't want to muddy the waters, so I'll be omitting a considerable amount of detail. Once you're comfortable with a topic, and have done it a few times yourself, I recommend going back and reading through the official Python documentation on the topic.\n" +
"\n" +
"A Note on Python Versions\n" +
"The official end-of-life for Python 2 is rapidly approaching, so you should learn and begin using Python 3 as soon as possible! This entire series is geared towards Python 3, with a bias towards 3.6 and 3.7, except as otherwise noted.\n" +
"\n" +
"Edits\n" +
"The articles in this series are frequently being reviewed by my fellow Python experts, and by the Dev community at large. I will expand and revise accordingly. Always check the edit timestamp at the top of the article.\n" +
"\n" +
"Roadmap\n" +
"The current series plan is below. Please note, I may rearrange, add, or remove planned sections."}
imageSrc={"https://insights.dice.com/wp-content/uploads/2017/09/shutterstock_315465929.jpg"}
authorImageSrc={"https://lh5.googleusercontent.com/--OlyHl449xI/AAAAAAAAAAI/AAAAAAAAAAA/ACevoQNk7ZZElQ_vKIQT_6d4HZw_wN3Qxg/mo/photo.jpg?sz=64"}
authorName={"Denis Ivanenko"}/>
</List>
</Box>
</Grid>
</Grid>
</div>
</React.Fragment>
);
}
ArticleCard.js
import React from "react";
import {red} from '#material-ui/core/colors';
import makeStyles from "#material-ui/core/styles/makeStyles";
import Card from "#material-ui/core/Card";
import CardHeader from "#material-ui/core/CardHeader";
import Avatar from "#material-ui/core/Avatar";
import IconButton from "#material-ui/core/IconButton";
import CardMedia from "#material-ui/core/CardMedia";
import CardContent from "#material-ui/core/CardContent";
import Typography from "#material-ui/core/Typography";
import CardActions from "#material-ui/core/CardActions";
import clsx from "clsx";
import FavoriteIcon from '#material-ui/icons/Favorite';
import ShareIcon from '#material-ui/icons/Share';
import Button from "#material-ui/core/Button";
const useStyles = makeStyles((theme) => ({
root: {
width:"155%",
gridColumn: "2/span 7"
},
media: {
height: 0,
paddingTop: '56.25%',
},
expand: {
transform: 'rotate(0deg)',
marginLeft: 'auto',
transition: theme.transitions.create('transform', {
duration: theme.transitions.duration.shortest,
}),
},
avatar: {
backgroundColor: red[500],
},
}));
export default function ArticleCard(props) {
const classes = useStyles();
const [expanded] = React.useState(false);
const title = props.title;
const date = props.dateTime;
const imageSrc = props.imageSrc;
const imageAlt = props.imageAlt;
const previewText = props.text.substring(0,158)+"...";
return (
<Card className={classes.root}>
<CardHeader
avatar={
<Avatar aria-label="recipe" className={classes.avatar}>
<img src={props.authorImageSrc} alt={props.authorName}/>
</Avatar>
}
title={title}
subheader={date}
/>
<CardMedia
className={classes.media}
image={imageSrc}
title={imageAlt}
/>
<CardContent>
<Typography variant="body2" color="textSecondary" component="p">
{previewText}
</Typography>
</CardContent>
<CardActions disableSpacing>
<IconButton aria-label="add to favorites">
<FavoriteIcon/>
</IconButton>
<IconButton aria-label="share">
<ShareIcon/>
</IconButton>
<Button
className={clsx(classes.expand, {
[classes.expandOpen]: expanded,
})}
aria-expanded={expanded}
aria-label="show more"
href={"/article"}
>
Read More
</Button>
</CardActions>
</Card>
);
}
This has got nothing to do with material-ui,
you've applied marginLeft: auto, which will not apply marginRight: auto, so it would not be center aligned
you should add marginRight: auto, as well to center it.
const useStyles = makeStyles({
root: {
flexGrow: 1,
},
tabpanel: {
marginLeft: "auto",
marginRight: "auto"
}
});

How to change material-ui Textfield label styles in react

I'm new to Material-UI, I couldn't able to figure it out, how to change the color of the label which is showing in grey color. I want it in black. Can anyone help me with this query?
Here is the Code :
import React from "react";
import ReactDOM from "react-dom";
import { TextField, Button, Grid } from "#material-ui/core";
class App extends React.Component {
render() {
return (
<Grid container justify={"center"} alignItems={"center"} spacing={1}>
<Grid item>
<TextField
id="outlined-name"
label="Name"
value={"Enter value"}
onChange={() => console.log("I was changed")}
margin="normal"
variant="outlined"
/>
</Grid>
<Grid item>
<Button variant="contained" color="primary">
Submit
</Button>
</Grid>
</Grid>
);
}
}
Here is the code: "https://codesandbox.io/s/fancy-morning-30owz"
If you use the selection tools in your browser, you would find out that:
The class name used is MuiFormLabel-root
<label class="MuiFormLabel-root MuiInputLabel-root MuiInputLabel-formControl MuiInputLabel-animated MuiInputLabel-shrink MuiInputLabel-outlined MuiFormLabel-filled" data-shrink="true" for="outlined-name">Name</label>
So set the styles using nesting selector to the TextField component
Functional component
import { makeStyles } from "#material-ui/core/styles";
const useStyles = makeStyles(theme => ({
root: {
"& .MuiFormLabel-root": {
color: "red" // or black
}
}
}));
...
const classes = useStyles();
Classical component
import { withStyles, createStyles } from "#material-ui/core/styles";
const styles = theme => createStyles({
root: {
"& .MuiFormLabel-root": {
color: "red"
}
}
});
...
const { classes } = this.props;
...
export default withStyles(styles)(App);
usage
<TextField
className={classes.root}
...
>
</TextField>
By this way, you can change the label color, as the screenshot is shown below (currently red)
Try it online:
If you want to leave your style in a separate file, you can write:
.MuiTextField-root > label {
background-color: $bg-color;
color: $color;
}
.MuiTextField-root > .MuiFormLabel-root.Mui-focused {
color: $color;
}

Categories

Resources