Give diferent className to MenuProps and Parent Select Componens with styled-components - reactjs

I'm trying to customize a MUI TextField Select component with styled components.
The ideia is styled-compoents provide diferent classes to Select field and Menu, so i can have their styled separated.
const StyledSelect = styled(({ className, ...props }) => {
return (
<TextField {...props}
classes={{ root: className }}
SelectProps={{
MenuProps: {
classes: { paper: className, list: className },
anchorOrigin: {
vertical: "bottom",
horizontal: "left"
},
transformOrigin: {
vertical: "top",
horizontal: "left"
},
getContentAnchorEl: null
},
}}
/>
)
})`
& {
background-color: #454D5D;
border-radius: 10px;
margin-top: 5px;
}
& li {
color: #FFF;
}
&.MuiFormControl-root {
background-color: transparent;
}
& .MuiListItem-root {
font-size: 18px;
}
& .MuiListItem-root.Mui-selected {
background-color: #1A2233;
}
& .MuiFormLabel-root {
font-family: 'Roboto';
font-weight: 300;
}
& .MuiInputLabel-shrink {
color: ${props => props.color};
font-weight: normal;
}
& .MuiInput-underline:after {
border-bottom: 2px solid ${props => props.errors[props.field.name] && props.touched[props.field.name]
? CASABLANCA : props.color};
transition: none;
transform: none;
}
& .MuiInput-underline:before {
border-bottom: 1px solid ${props => props.color}
}
& .MuiSelect-roo {
color: black;
font-family: 'Roboto';
font-weight: 300;
}
& .MuiSelect-select:focus {
background: transparent;
}
`;
I wish my TextField class would be different from MenuProps class

One way to solve this is to have one wrapper component per class name you need to generate. In my example below, StyledTextField takes care of the root class name for TextField (the className property is equivalent to classes.root) and then MenuPaperClass provides an additional class name.
import React from "react";
import ReactDOM from "react-dom";
import TextField from "#material-ui/core/TextField";
import MenuItem from "#material-ui/core/MenuItem";
import styled from "styled-components";
const StyledTextField = styled(TextField)`
/* && to add specificity */
&& {
border: 1px solid green;
}
`;
const MenuPaperClass = styled(({ className, ...props }) => {
return (
<StyledTextField
SelectProps={{ MenuProps: { classes: { paper: className } } }}
value="1"
select
{...props}
>
<MenuItem value="1">One</MenuItem>
<MenuItem value="2">Two</MenuItem>
<MenuItem value="3">Three</MenuItem>
</StyledTextField>
);
})`
&& {
background-color: lightblue;
}
`;
function App() {
return (
<div className="App">
<MenuPaperClass />
</div>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
This isn't a particularly elegant solution and gets pretty tedious if you have 3 or more separate classes you want to use, so I may come back to this later to consider alternative approaches/syntax, but this does work.

Related

How can React Js make a Border-botom as a function?

I would like to give Border-bottom as a function. What should I do?
This is the code that Border-bottom should appear.๐Ÿ‘‡
import React from "react";
import { Header } from "../BaseLabel";
import { Link, withRouter } from "react-router-dom";
const Header = ({ location: { pathname } }) => {
const getStyle = (path) => {
return {
color: pathname === path ? "#191919" : "#B6B6B6",
borderBottom: pathname === path ? "#191919" : null,
};
};
return (
<>
<ShapMenu>
<ShapLinks to="/covid19" style={getStyle("/covid19")}> //Link
<Header title="์ฝ”๋กœ๋‚˜19" current={pathname === "/covid19"} />
</ShapLinks>
</ShapMenu>
</>
);
}
This is Header Styled-components๐Ÿ‘‡
const ShapMenu = styled.div`
display: flex;
box-sizing: content-box;
overflow-x: scroll;
overflow-y: hidden;
white-space: nowrap;
scroll-behavior: smooth;
scrollbar-color: inherit;
cursor: pointer;
`;
const ShapLinks = styled(Link)``;
This is a reusable component code. This code is not only used on this screen because it is a reuse code.๐Ÿ‘‡
import PropTypes from "prop-types";
import styled from "styled-components";
import React from "react";
export const Header = ({ title, children }) => {
return (
<>
<Title>{title}</Title>
<Items>{children}</Items>
</>
);
};
Header.propTypes = {
title: PropTypes.node,
children: PropTypes.object,
};
const Items = styled.div``;
const Title = styled.div`
margin-right: 14px;
font-size: 20px;
`;
This is the style property that I want to give to the title.๐Ÿ‘‡
border-bottom: 2px solid
${(props) => (props.current ? "#191919" : "transparent")};
transition: border-bottom 0.5s ease-in-out;
The CSS styled rules appear to be correct. You should pass the current prop from Header to Title.
const Header = ({ current, title, children }) => { // <-- destructure current
return (
<>
<Title current={current}>{title}</Title> // <-- pass current prop
<Items>{children}</Items>
</>
);
};
Header.propTypes = {
children: PropTypes.object,
current: PropTypes.bool,
title: PropTypes.node
};
const Title = styled.div`
margin-right: 14px;
font-size: 20px;
border-bottom: 2px solid
${(props) => (props.current ? "#191919" : "transparent")}; // <-- use current prop
transition: border-bottom 0.5s ease-in-out;
`;

Increase min-width of item - material ui (custom component)

Component which i have built
// libs
import React from 'react';
// material components
// styles
import {
StyledSelect,
StyledFormControl,
StyledMenuList,
ISelectProps,
} from './styles';
function Select(props: ISelectProps) {
const {
displayEmpty,
iconBordered,
options,
value,
children,
onChange,
className,
} = props;
return (
<StyledFormControl className={className}>
<StyledSelect
MenuProps={{
classes: { paper: 'Menupaper' },
anchorOrigin: {
vertical: 'bottom',
horizontal: 'left',
},
getContentAnchorEl: null,
}}
IconComponent={(props) => {
let iconClass = 'icon-container';
if (props.className.split(' ').indexOf('MuiSelect-iconOpen') > -1) {
iconClass += ' icon-rotate';
}
iconClass += ` ${props.className}`;
return (
<>
<span className="icon-border" />
<span className={iconClass}>
<i className="icon-arrow-down icon-rotate" />
</span>
</>
);
}}
autoWidth
iconBordered={iconBordered}
displayEmpty={displayEmpty}
onChange={onChange}
variant="outlined"
value={value}
>
{!!options
? options.map(({ value, label }) => (
<StyledMenuList disableRipple value={value}>
{label}
</StyledMenuList>
))
: children}
</StyledSelect>
</StyledFormControl>
);
}
export default Select;
Accessing the component:
<FormField>
<Left>
<Label>{t('search_pane.status')}</Label>
<Select
displayEmpty
menuClass="menu"
className="searchSelect"
value={chatState}
onChange={handleChatStatusChange}
options={Object.keys(CHAT_STATE_OPTIONS).map((el) => {
return { value: el, label: CHAT_STATE_OPTIONS[el] };
})}
/>
</Left>
<Right>
<Label>{t('search_pane.date')}</Label>
<Select
className="searchSelect"
menuClass="menu"
value={date}
onChange={handleDateChange}
options={Object.keys(DATE_OPTIONS).map((el) => {
return { value: el, label: DATE_OPTIONS[el] };
})}
/>
</Right>
</FormField>
Style of the MenuList:
export const StyledMenuList = styled(MenuItem)`
min-width: 125px;
margin-left: 6px;
margin-right: 6px;
padding-left: 8px;
font-size: ${({ theme }) => theme.font.sizes[500]};
color: ${({ theme }) => theme.colors.SECONDARY[600]};
transition: all 300ms ease;
transition-property: background-color, color;
&:focus {
background-color: ${({ theme }) => theme.colors.WHITE};
}
&:hover {
background-color: ${({ theme }) => theme.colors.PRIMARY[100]} !important;
color: ${({ theme }) => theme.colors.PRIMARY[600]};
border-radius: 4px;
}
`;
I want my min-width to be changeable from where I am calling the component
const FormField = styled.div`
display: flex;
margin-top: 18px;
margin-bottom: ${({ theme }) => theme.spacing[400]};
width: 100%;
.searchSelect {
width: 100%;
margin-top: 7px;
height: ${({ theme }) => theme.spacing[700]};
.MuiOutlinedInput-root {
height: ${({ theme }) => theme.spacing[700]};
}
.icon-container {
top: 22px;
}
li {
min-width: 192px;
}
}
`;
All the css changes takes effect except the li 192px can someone help?
I have tried passing a menuClass css etc but nothing has worked
EDIT:
I have also tried:
<StyledMenuList
classes={{ root: menuClass }}
disableRipple
value={value}
>
{label}
</StyledMenuList>
passing menuClass via props
Without a codesandbox it is a little harder, providing one would be of great help.
My suggest based on how material-ui Select works is that your li-MenuItems are not in the same DOM level as the .searchSelect element as your styling expects and that's why your styling is not getting applied.
Try to put it outside - something like this:
const FormField = styled.div`
...
.searchSelect {
width: 100%;
margin-top: 7px;
height: ${({ theme }) => theme.spacing[700]};
.MuiOutlinedInput-root {
height: ${({ theme }) => theme.spacing[700]};
}
.icon-container {
top: 22px;
}
}
li {
min-width: 192px;
}
`;

implementing dark mode with Themeprovider and styled components

I don't know much about styled-components, I am using a toggle switch to change themes and my theme does switch from dark to light but the icons I'm using don't switch icons. The icons are valid, when I switch the order of the component the Moon icon shows only instead, I'm guessing this is something with syntax?
import React from 'react'
import { func, string } from 'prop-types';
import styled from 'styled-components';
import { ReactComponent as MoonIcon } from '../components/icons/moon.svg';
import { ReactComponent as SunIcon } from '../components/icons/sun.svg';
const ToggleContainer = styled.button`
background: ${({ theme }) => theme.gradient};
border: 2px solid ${({ theme }) => theme.toggleBorder};
border-radius: 30px;
cursor: pointer;
display: flex;
font-size: 0.5rem;
justify-content: space-between;
margin: 0 auto;
overflow: hidden;
padding: 0.5rem;
position: relative;
width: 8rem;
height: 4rem;
svg {
height: auto;
width: 2.5rem;
transition: all 0.3s linear;
// sun icon
&:first-child {
transform: ${({ lightTheme }) => lightTheme ? 'translateY(0)' : 'translateY(100px)'};
}
// moon icon
&:nth-child(2) {
transform: ${({ lightTheme }) => lightTheme ? 'translateY(-100px)' : 'translateY(0)'};
}
}
`;
const Toggle = ({ theme, toggleTheme }) => {
const isLight = theme === 'light';
return (
<ToggleContainer onClick={toggleTheme} >
<MoonIcon />
<SunIcon />
</ToggleContainer>
);
};
Toggle.propTypes = {
theme: string.isRequired,
toggleTheme: func.isRequired,
}
export default Toggle;
lightmode
darkmode
Add lightTheme={isLight} to this code
At: <ToggleContainer onClick={toggleTheme} >
Final: <ToggleContainer onClick={toggleTheme} lightTheme={isLight}>
Also, you can play with transform like below for switching between,
`&:first-child {
transform: ${({ lightTheme }) => lightTheme ? 'translateX(0px)' : 'translateX(-150px)'};
}
&:nth-child(2) {
transform: ${({ lightTheme }) => lightTheme ? 'translateX(100px)' : 'translateX(0px)'};
}`

React - styled-components, props, and TypeScript

I looking into styled-components and trying the examples from the website but I also wanted to use TypeScript.
I have this simple example here
import React from 'react';
import './App.css';
import styled from 'styled-components';
interface IProps{
primary: boolean
}
const App:React.FC<IProps> = ({primary}) => {
return (
<div className="App">
<h1>Styled Components</h1>
<Button>Normal</Button>
<Button primary>Primary</Button>
</div>
);
}
const Button = styled.button`
background: ${props => props.primary ? 'red' : 'white'};
color: ${props => props.primary ? 'white' : 'red'};
font-size: 1em;
margin: 1em;
padding: 0.25em 1em;
border: 1px solid green;
border-radius: 3px;
`
export default App;
but I'm getting errors on the primary prop
I getting the error
Property 'primary' does not exist on type 'ThemedStyledProps<Pick<DetailedHTMLProps<ButtonHTMLAttributes<HTMLButtonElement>, HTMLButtonElement>, "form" | ... 264 more ... | "onTransitionEndCapture"> & { ...; }, any>'
Ho can I use styled-components with TypeScript?
Use styled-components with typescript:
const Button = styled.button<{ primary?: boolean }>`
Full code:
import * as React from 'react';
import styled from 'styled-components';
interface IProps{
primary?: boolean
}
const App:React.FC<IProps> = () => {
return (
<div className="App">
<h1>Styled Components</h1>
<Button>Normal</Button>
<Button primary>Primary</Button>
</div>
);
}
const Button = styled.button<{ primary?: boolean }>`
background: ${props => props.primary ? 'red' : 'white'};
color: ${props => props.primary ? 'white' : 'red'};
font-size: 1em;
margin: 1em;
padding: 0.25em 1em;
border: 1px solid green;
border-radius: 3px;
`
export default App;
I prepare a example from my project
Wrapper.ts(styled-component)
import styled from 'styled-components';
interface Props {
height: number;
}
export const Wrapper = styled.div<Props>`
padding: 5%;
height: ${(props) => props.height}%;
`;
index.tsx
import React, { FunctionComponent } from 'react';
import { Wrapper } from './Wrapper';
interface Props {
className?: string;
title: string;
height: number;
}
export const MainBoardList: FunctionComponent<Props> = ({ className, title, height }) => (
<Wrapper height={height} className={className}>
{title}
</Wrapper>
);
you can import interface/type from 'index.tsx' to 'Wrapper.ts' to reuse.
other wise you can specify type like this
export const Wrapper = styled.div<{height:number}>`

React Styled-Components passing props issue

Trying to create a nested component that accepts multiple arguments, eg. styles for the button, styles for text and a possible icon. Everything (passing props) works fine if I directly render the button.
Below is the code I've written
import React from "react";
import styled from "styled-components";
import _ from "lodash";
import { hexToRgb } from "../styles/helpers";
import * as MaterialIcons from "styled-icons/material";
const StyledButton = styled.button`
text-align: center;
border: ${props =>
props.outline ? `1px solid ${props.outlineColor}` : "none"};
background: ${props => (props.background ? props.background : "#000")};
border-color: ${props =>
props.outlineColor ? props.outlineColor : "transparent"};
min-width: 120px;
width: ${props => (props.width ? props.width : "auto")};
min-height: 40px;
border-radius: 25px;
color: ${props => (props.color ? props.color : "#FFF")};
transition: all ease 0.5s;
&:hover {
cursor: pointer;
background: ${props =>
props.background ? hexToRgb(props.background) : "#FFF"};
}
`;
const StyledText = styled.span`
font-size: 16px;
font-weight: ${props => (props.fontWeight ? props.fontWeight : 400)};
`;
const StyledIcon = styled(MaterialIcons.Lock)`
font-size: 15;
padding: 10px;
`;
const Button = props => {
let _icon = null;
const { children, icon } = props;
console.log("props", props);
if (icon) {
_icon = <StyledIcon size="48" title="Test icon" />;
}
console.log("StyledButton", StyledButton);
return (
<StyledButton>
<StyledText>{children}</StyledText>
{_icon}
</StyledButton>
);
};
export default Button;
If I directly export default StyledButton it works fine.
For some odd reason props were not passed onto the StyledComponent, however directly stating what I want works.
return (
<StyledButton
outlineColor={outlineColor}
background={background}
width={width}
color={color}
outline={outline}
>
<StyledText>{children}</StyledText>
{_icon}
</StyledButton>
);

Resources