Skip to content

Instantly share code, notes, and snippets.

@gauravsoti1
Last active September 1, 2022 04:58
Show Gist options
  • Save gauravsoti1/1e8c803404ceb611cad0608f18c718ae to your computer and use it in GitHub Desktop.
Save gauravsoti1/1e8c803404ceb611cad0608f18c718ae to your computer and use it in GitHub Desktop.
Styling Material Ui's Avatar for a project to have different size which adjusts according to screen sizes. Also, gutter spacing on left and right. Libraries: React, material ui, styled-components
import React from "react";
import styled, { css } from "styled-components";
import { Avatar } from "@material-ui/core";
// -------------------------- Defining all the css sizes ------------------------
export const SmallestSizeCSS = css`
width: 30px;
height: 30px;
${props => props.theme.breakpoints.up("lg")} {
width: 35px;
height: 35px;
}
`;
export const SmallerSizeCSS = css`
width: 36px;
height: 36px;
${props => props.theme.breakpoints.up("lg")} {
width: 44px;
height: 44px;
}
`;
export const SmallSizeCSS = css`
width: 40px;
height: 40px;
${props => props.theme.breakpoints.up("lg")} {
width: 50px;
height: 50px;
}
`;
export const MediumSizeCSS = css`
width: 60px;
height: 60px;
${props => props.theme.breakpoints.up("lg")} {
width: 80px;
height: 80px;
}
`;
export const BigSizeCSS = css`
width: 120px;
height: 120px;
${props => props.theme.breakpoints.up("lg")} {
width: 150px;
height: 150px;
}
`;
// --------------------------------------------------------------------
// Using object to easily access those css styles
export const ImageSizesCSS = {
smallest: SmallestSizeCSS,
smaller: SmallerSizeCSS,
small: SmallSizeCSS,
big: BigSizeCSS,
medium: MediumSizeCSS
};
// gutter is the margin
export function StyledAvatar({ size, rightGutter, leftGutter, ...props }) {
return (
<AvatarContainer
size={size}
leftGutter={leftGutter}
rightGutter={rightGutter}
{...props}
/>
);
}
const AvatarContainer = styled(Avatar)`
${props => ImageSizesCSS[props.size] }; // geting the sizes css object according to the size provided
${props =>
props.rightGutter &&
css`
margin-right: ${props => props.theme.spacing(1)}rem;
`}
${props =>
props.leftGutter &&
css`
margin-left: ${props => props.theme.spacing(1)}rem;
`}
`;
StyledAvatar.defaultProps = {
size: "medium",
leftGutter: false,
rightGutter: false
};
StyledAvatar.propTypes = {
leftGutter: PropTypes.bool,
rightGutter: PropTypes.bool,
size: PropTypes.oneOf(["small", "medium", "smaller", "smallest", "big"])
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment