Proper way of passing classes into child components in MUI? - css

I was using material-UI, but then I decided to migrate to MUI. Which I found was complicated change because.
Material UI format
import { makeStyles } from "#material-ui/core";
export const useStyles = makeStyles((theme) => ({
root: {
display: 'flex',
// alignItems: 'center',
width: '100%',
position: 'relative',
// backgroundColor: '#C2C2C2',
// marginTop: '700px',
height: theme.spacing(65)
// color: 'white',
// justifyContent: 'space-between'
},
}));
TO
MUI Format
import { makeStyles } from '#mui/styles';
import { styled } from '#mui/material/styles';
export const useStyles = () => ({
Root: styled('div')(({theme}) => ({
height: theme.spacing(10),
display: 'flex',
alignItems: 'center',
width: '100%',
position: 'relative',
color: 'white',
justifyContent: 'space-between',
[theme.breakpoints.down('xs')]: {
// justifyContent: 'center'
padding: '0 10px 0 10px'
}
})),
Logo: styled('div')(({theme}) => ({
display: 'flex',
alignItems: 'center',
gap: '1em',
letterSpacing: '0.5em',
"& h4": {
fontSize: '1.8em'
},
[theme.breakpoints.up('sm')]: {
marginLeft: '2em',
}
})),
})
Which is fine, but the problem is that earlier, I had some components like this.
<AnimeLogoWhite className={classes.logoIcon} />
Now, this component simply took the class logoIcon and applied it.
logoIcon: {
height: theme.spacing(6),
position: 'relative',
// iphone SE custom breakpoint
[theme.breakpoints.down(325)]: {
height: theme.spacing(5)
}
},
AnimeLogoWhite.tsx
import { FC } from 'react';
import whiteLogo from '../../../public/arkAnimeLogoWhite.svg';
interface Props {
className: string
}
export const AnimeLogoWhite: FC<Props> = ({className}) => {
return(
<img className={className} src={whiteLogo.src} alt='' />
)
}
I can't do this further with MUI.
Can anyone help me on how to achieve something similar?

Related

Align items to the left and right in React Native

How do you align items to the left and the right in React Native?
Whatever combination of flexbox properties I try, the two sets of text are stuck next to each other like this:
How do you make it so "Sign In" is on the right side of the screen and Repositories on the left?
Here is my code:
import { View, StyleSheet, Text, ScrollView } from 'react-native';
import Constants from 'expo-constants';
import { Link } from "react-router-native";
const styles = StyleSheet.create({
container: {
paddingTop: Constants.statusBarHeight,
paddingLeft: 10,
paddingBottom: 20,
backgroundColor: 'grey',
},
text: {
fontSize: 20,
color: 'white',
fontWeight: 'bold'
},
linkText: {
color: 'white',
},
nesteddivleft: {
flex: 1,
display: "flex",
justifyContent: "flex-start",
alignItems: "center",
},
nesteddivright: {
flex: 1,
display: "flex",
justifyContent: "flex-end",
alignItems: "center",
},
scrollbar: {
display: 'flex',
justifyContent: 'space-between'
}
});
const AppBar = () => {
return <><View style={styles.container}>
<ScrollView style="scrollview" horizontal>
<View style={styles.nesteddivleft}><Link to="/"><Text style={styles.text}>Repositories</Text></Link></View>
<View style={styles.nesteddivright}><Link to="/signin"><Text style={styles.linkText}>Sign In</Text></Link></View>
</ScrollView>
</View>
</>
};
export default AppBar;
App:
import Main from './src/components/Main'
import { StatusBar } from 'expo-status-bar';
import { NativeRouter } from 'react-router-native';
export default function App() {
return (
<>
<NativeRouter>
<Main/>
</NativeRouter>
<StatusBar style="auto" />
</>
);
}
As you can see, I have tried putting justify-content: space-between on the parent div and that does nothing.
I also tried this solution and it has done nothing: Aligning elements left, center and right in flexbox
import { View, StyleSheet, Text, ScrollView } from 'react-native';
import Constants from 'expo-constants';
import { Link } from "react-router-native";
const styles = StyleSheet.create({
container: {
paddingTop: Constants.statusBarHeight,
paddingLeft: 10,
paddingBottom: 20,
backgroundColor: 'grey',
display: "flex",
justifyContent: "space-between",
minWidth: '100%',
flexDirection: "row"
},
text: {
fontSize: 20,
color: 'white',
fontWeight: 'bold'
},
linkText: {
color: 'white',
},
nesteddivleft: {
},
nesteddivright: {
},
scrollbar: {
}
});
const AppBar = () => {
return <><View style={styles.container}>
<View style={styles.nesteddivleft}><Link to="/"><Text style={styles.text}>Repositories</Text></Link></View>
<View style={styles.nesteddivright}><Link to="/signin"><Text style={styles.linkText}>Sign In</Text></Link></View>
</View>
</>
};
export default AppBar;
Steps to solve issue:
Take out the scrollview component.
set Display to flex, justify Content to space-between, minWidth to 100% AND flex Direction to Row in parent component.
Not optimal as I need the Scrollview component in there as well, I will need to find a solution that allows me to have that component as a child.

Material UI Advanced Button - Text Alignment for Small Screensizes

React / Material-UI Novice here. I am trying to configure a set of buttons inside my app Bar that have a background picture to make it look a little cleaner. I have used a lot of code from examples online (shock) and got it to a place where i am happy with how it has formatted on a full size view (md++). However, when i downsize it to a small breakpoint though, the button image then stack instead (which is what i want) but i lose my text to the left. I have tried shifting to the right in many different ways but i dont think thats the right way to do it, is there something i am missing in making the text flex, i want the text to be in the middle?
import React from 'react'
import { AppBar, Toolbar } from "#mui/material";
import { makeStyles } from '#mui/styles'
import Button from '#mui/material/Button'
import Stack from '#mui/material/Stack'
import ButtonBase from '#mui/material/ButtonBase';
import { styled } from '#mui/material/styles';
import Typography from '#mui/material/Typography';
import Box from '#mui/material/Box';
const useStyles = makeStyles(theme => ({
button: {
...theme.typography.mainmenu,
borderRadius: "40px",
marginLeft: "1px",
height: "45px",
"&:hover": {
backgroundColor: theme.palette.secondary
}
},
}))
const images = [
{
url: '/assets/breakfastMenu.jpg',
title: 'Breakfast',
width: '33.33%',
},
{
url: '/assets/steak.jpg',
title: 'Mains',
width: '33.33%',
},
{
url: '/assets/desserts.jpg',
title: 'Desserts',
width: '33.33%',
},
];
const Image = styled('span')(({ theme }) => ({
position: 'absolute',
left: 0,
right: 0,
top: 0,
bottom: 0,
display: 'flex',
alignItems: 'center',
justifyContent: 'space-between',
color: theme.palette.common.primary,
}));
const ImageButton = styled(ButtonBase)(({ theme }) => ({
position: 'relative',
height: 150,
[theme.breakpoints.down('sm')]: {
width: '100% !important', // Overrides inline-style
height: 100,
},
'&:hover, &.Mui-focusVisible': {
zIndex: 1,
'& .MuiImageBackdrop-root': {
opacity: 0.15,
},
'& .MuiImageMarked-root': {
opacity: 0,
},
'& .MuiTypography-root': {
border: '4px solid currentColor',
},
},
}));
const ImageSrc = styled('span')({
position: 'absolute',
left: 0,
right: 0,
top: 0,
bottom: 0,
backgroundSize: 'cover',
backgroundPosition: 'center 40%',
});
const ImageBackdrop = styled('span')(({ theme }) => ({
position: 'absolute',
left: 0,
right: 0,
top: 0,
bottom: 0,
backgroundColor: theme.palette.common.black,
opacity: 0.4,
transition: theme.transitions.create('opacity'),
}));
const ImageMarked = styled('span')(({ theme }) => ({
height: 3,
width: 18,
backgroundColor: theme.palette.common.white,
position: 'absolute',
bottom: -2,
left: 'calc(50% - 9px)',
transition: theme.transitions.create('opacity'),
}));
const Header = () => {
const classes = useStyles();
return (<React.Fragment><AppBar position="sticky" className={classes.appBar}>
<Toolbar disableGutters className={classes.mainToolbar} sx={{ justifyContent: "center" }}>
<Stack direction="row" justifyContent="space-between" alignItems="center" spacing={10}>
{/* <Button variant="contained" color="secondary" className={classes.button}>Breakfast</Button>
<Button variant="contained" color="secondary" className={classes.button}>Mains</Button>
<Button variant="contained" color="secondary" className={classes.button}>Desserts</Button> */}
<Box sx={{ display: 'flex', flexWrap: 'wrap', minWidth: 900, width: '100%' }}>
{images.map((image) => (
<ImageButton
focusRipple
key={image.title}
style={{
width: image.width,
}}
>
<ImageSrc style={{
backgroundImage: `url(${image.url})`
}} />
<ImageBackdrop className="MuiImageBackdrop-root" />
<Image>
<Typography
component="span"
variant="subtitle1"
color="white"
fontWeight="bold"
sx={{
position: 'relative',
p: "7em",
pt: "2em",
pb: (theme) => `calc(${theme.spacing(1)} + 6px)`,
}}
>
{image.title}
<ImageMarked className="MuiImageMarked-root" />
</Typography>
</Image>
</ImageButton>
))}
</Box>
</Stack>
</Toolbar>
</AppBar>
</React.Fragment >
)
}
export default Header
I have moved on from this, but in case anybody finds it, using MUI i completely adapted my application by using:
import useMediaQuery from '#mui/material/useMediaQuery'
and some example like:
const matches = useMediaQuery(theme.breakpoints.down("md"))
to control when the application changes its styles

Icon button with InputBase

I'm a newbie to MUI/react and I've been trying to place an Icon button beside my input base form, however I'm struggling to make it so that the input form consumes all the available space in my search div. Instead my search icon wrapper is the one that takes majority of the space. I'm really confused what I'm doing wrong, Can someone please shed some light on me?
Here's my code:
import * as React from "react";
import { styled } from "#mui/material/styles";
import Box from "#mui/material/Box";
import InputBase from "#mui/material/InputBase";
import SearchIcon from "#mui/icons-material/Search";
import IconButton from "#mui/material/IconButton";
const Search = styled("div")(({ theme }) => ({
display: "flex",
position: "relative",
borderRadius: 30,
backgroundColor: "#ffffff",
border: "1px",
borderStyle: "solid",
borderColor: "#55597d",
// marginLeft: 10,
width: "auto",
".MuiInputBase-root": {
width: "100%",
},
}));
const SearchIconWrapper = styled("div")(({ theme }) => ({
padding: theme.spacing(0, 2),
height: "100%",
// position: 'absolute',
// pointerEvents: 'none',
display: "flex",
alignItems: "center",
justifyContent: "flex-end",
// backgroundColor: 'black',
width: "100%",
}));
const StyledInputBase = styled(InputBase)(({ theme }) => ({
color: "inherit",
"& .MuiInputBase-input": {
padding: theme.spacing(1, 1, 1, 0),
// vertical padding + font size from searchIcon
paddingLeft: `calc(1em + ${theme.spacing(0)})`,
paddingRight: `calc(1em + ${theme.spacing(4)})`,
transition: theme.transitions.create("width"),
width: "100%",
},
}));
export default function SearchAppBar({
searchQuery,
setSearchQuery,
clearGenre,
onDropDownChange,
}) {
return (
<Box sx={{ flexGrow: 1 }}>
<Search
sx={{
width: { xs: "90vw", md: "50vw", lg: "30vw" },
margin: "auto",
marginBottom: "20px",
}}
>
<form action="/" method="get">
<StyledInputBase
defaultValue={searchQuery}
// placeholder="Search All Games…"
inputProps={{ "aria-label": "search" }}
type="search"
name="s"
id="site-search"
/>
</form>
<SearchIconWrapper>
<IconButton>
<SearchIcon style={{ color: "#55597d" }} />
</IconButton>
</SearchIconWrapper>
</Search>
</Box>
);
}
You need to remove the width: 100% in the SearchIconWrapper on the right first. And because the Search component is a flex container, you also need to add flexGrow: 1 to the first child (the form) so it can expand to fit the parent and push the icon to the far right:
const Search = styled("div")(({ theme }) => ({
display: "flex",
position: "relative",
borderRadius: 30,
backgroundColor: "#ffffff",
border: "1px",
borderStyle: "solid",
borderColor: "#55597d",
// marginLeft: 10,
// ---------------------------------- add the following styles
"& :first-child": {
flexGrow: 1
}
width: "auto",
".MuiInputBase-root": {
width: "100%"
}
}));
const SearchIconWrapper = styled("div")(({ theme }) => ({
padding: theme.spacing(0, 2),
height: "100%",
// position: 'absolute',
// pointerEvents: 'none',
display: "flex",
alignItems: "center",
justifyContent: "flex-end"
// backgroundColor: 'black',
// -----------------------------------> comment this line: width: "100%"
}));

Applying css on a imported react component

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;

How to make Material-UI Snackbar not take up the whole screen width using anchorOrigin?

I have a class in React which uses an input field which is part of the website header:
If the input is invalid then I want to display a snackbar. I'm using Material-UI components.
The problem is I defined anchorOrigin to be center and top as per Material-UI API. However the snackbar takes up the whole screen width while I want it to only take up the top center location of the screen. My message is quite short, for example "Value invalid" but if it's longer then I should be able to use newlines. I'm not sure if there's some setting in Material-UI API to alter this (I couldn't find one) or I need to use CSS.
This is my code:
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import InputBase from '#material-ui/core/InputBase';
import Snackbar from '#material-ui/core/Snackbar';
import SnackbarMessage from './SnackbarMessage.js';
const classes = theme => ({
inputRoot: {
color: 'inherit',
width: '100%',
},
inputInput: {
paddingTop: theme.spacing.unit,
paddingRight: theme.spacing.unit,
paddingBottom: theme.spacing.unit,
paddingLeft: theme.spacing.unit * 10,
transition: theme.transitions.create('width'),
width: '100%',
[theme.breakpoints.up('sm')]: {
width: 120,
'&:focus': {
width: 200,
},
},
}
});
class Test extends Component {
state = {
appId: '',
snackBarOpen: false
}
render() {
return (
<div>
<InputBase
placeholder="Search…"
classes={{
root: classes.inputRoot,
input: classes.inputInput,
}}
value={'test'} />
<Snackbar
anchorOrigin={{
vertical: 'top',
horizontal: 'center'
}}
open={true}
autoHideDuration={5000}
>
<SnackbarMessage
variant="warning"
message={"test message"}
/>
</Snackbar>
</div>
)
}
}
Material-UI set Snackbars to full viewport-width below the breakpoint "md" (600px).
You can use overrides (https://material-ui.com/customization/overrides/) and set new values to the default CSS classes of the component described in the components API (i.e. https://material-ui.com/api/snackbar/). So you can override the class anchorOriginTopCenter as follows:
const styles = theme => ({
anchorOriginTopCenter: {
[theme.breakpoints.down('md')]: {
top: "your value/function here",
justifyContent: 'center',
},
},
root: {
[theme.breakpoints.down('md')]: {
borderRadius: 4,
minWidth: "your value / function here",
},
},
});
The first objects overrides the default class {anchorOriginTopCenter}, the second 'root' is applied to first element in your snackbar (probably a 'div').
I do not know if we can add some style to the component anchor origin field. I think the div needs to be managed using CSS. It's an anchor, not style.
<Snakbar
className = "my-snakbar"
{/*All your other stuff*/}
>
{//Stuff}
</Snakbar>
CSS
.my-snakbar {
width: 200px;
//Maybe use flexbox for positioning then
}
Let me know your thoughts
Daniel
Improved Answer
Code copied from origional question and modified
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import Snackbar from '#material-ui/core/Snackbar';
const classes = theme => ({
inputRoot: {
color: 'inherit',
width: '100%',
},
inputInput: {
paddingTop: theme.spacing.unit,
paddingRight: theme.spacing.unit,
paddingBottom: theme.spacing.unit,
paddingLeft: theme.spacing.unit * 10,
transition: theme.transitions.create('width'),
width: '100%',
[theme.breakpoints.up('sm')]: {
width: 120,
'&:focus': {
width: 200,
},
},
}
});
class ComingSoon extends Component {
render() {
const styles = {
container: {
position: "fixed",
top: "0px",
width: "100%",
height: "30px"
},
snakbar: {
background: "black",
color: "white",
width: "100px",
height: "100%",
display: "flex",
justifyContent: "center",
alignContent: "center",
margin: "0 auto"
}
};
return (
<div className = "snakbar-container" style = {styles.container}>
<Snackbar
className = "my-snakbar"
style = {styles.snakbar}
anchorOrigin={{
vertical: 'top',
horizontal: 'center'
}}
open={true}
autoHideDuration={5000}
>
<span>My Message</span>
</Snackbar>
</div>
)
}
}
export default ComingSoon;
Screen shot:
Let me know if this helped
Daniel

Resources