What does the symbol '&$checked' mean - javascript

import React from 'react';
import Checkbox from '#material-ui/core/Checkbox';
import { createMuiTheme, makeStyles, ThemeProvider } from '#material-ui/core/styles';
import { orange } from '#material-ui/core/colors';
const useStyles = makeStyles(theme => ({
root: {
color: theme.status.danger,
'&$checked': {
color: theme.status.danger,
},
},
checked: {},
}));
function CustomCheckbox() {
const classes = useStyles();
return (
<Checkbox
defaultChecked
classes={{
root: classes.root,
checked: classes.checked,
}}
/>
);
}
const theme = createMuiTheme({
status: {
danger: orange[500],
},
});
export default function CustomStyles() {
return (
<ThemeProvider theme={theme}>
<CustomCheckbox />
</ThemeProvider>
);
}
What does the symbol '&$checked' mean used in this CodeSandbox?
Please explain the meaning of each symbol in detail, and the related logic.
Thanks for answering.

The & is a reference to the parent rule ("root" in this case). $ruleName (where "ruleName" is "checked" in this case) references a local rule in the same style sheet.
To clarify some of the terms above, the parameter to makeStyles is used to generate a style sheet potentially with multiple style rules. Each object key (e.g. "root", "checked") is referred to as a "rule name". When you call useStyles the resulting classes object contains a mapping of each rule name to a generated CSS class name.
So in this case let's say that the generated class name for "root" is "root-generated-1" and the generated class name for "checked" is "checked-generated-2", then &$checked is equivalent to .root-generated-1.checked-generated-2 meaning it will match an element that has both the root and checked classes applied to it.
As far as the effect on the Checkbox, the "checked" class is applied to the Checkbox by Material-UI when it is in a "checked" state. This style rule is overriding the default color of a checked Checkbox (the default is the secondary color in the theme).
Related answers and documentation:
https://cssinjs.org/jss-plugin-nested?v=v10.0.0#use--to-reference-selector-of-the-parent-rule
https://cssinjs.org/jss-plugin-nested?v=v10.0.0#use-rulename-to-reference-a-local-rule-within-the-same-style-sheet
Internal implementation of "makeStyles" in React Material-UI?

'&$checked' means you can override the element after checked.
And in your case, you are overriding the colour of checkbox after checked it
"&$checked": {
color: theme.status.danger
}
PFA for detail

You are probably referring to the .color>*:checked element

Related

Fontawesome icons not accepting color props through react functional components via tailwindcss

My Problem
I have a project which requires icons everywhere. Instead of rendering a Fontawesome Icon in every script, I have a functional component which renders an icon when given props.
When calling the function, sometimes it doesn't accept the color prop. Only certain colors seem to be working, such as darkBlue, lightBlue, and green. Colors which haven't accepted the prop are defaulting to white.
I'm using Tailwindcss to inject classes into the components.
Tailwind Config
module.exports = {
content: ["./src/**/*.{js,jsx,ts,tsx}"],
theme: {
colors: {
dark: "#121212",
white: "#fff",
secondary: "#F0A500",
lightBlue: "#0EA5E9",
darkBlue: "#2563EB",
beige: "#FDBA74",
silver: "#9CA3AF",
red: "#DC2626",
green: "#10B981",
orange: "#F97316",
hotPink: "#EC4899",
purple: "#6D28D9",
yellow: "#FDE047",
},
extend: {
},
},
plugins: [],
};
FC: Icon Render
import React from "react";
import { FontAwesomeIcon } from "#fortawesome/react-fontawesome";
// color props must be passed as a string
function Icon({ name, color, scale }) {
return (
<FontAwesomeIcon
icon={name}
className={`text-${color}`}
size={scale}
/>
);
}
export default Icon;
Calling Icon Render
import React from "react";
import Button from "../../shared/components/Button";
import Typography from "../../shared/utilities/Typography";
import Mugshot from "../../shared/assets/mugshot.jpg";
import Icon from "../../shared/components/Icon";
import {
faGlobe,
faHandSpock,
faComment,
} from "#fortawesome/free-solid-svg-icons";
import Avatar from "../../shared/components/Avatar";
function example() {
return (
<section className="section" id="home-hero">
<Typography variant="label">Some text</Typography>
<Typography variant="h2">
Some text <Icon name={faHandSpock} color="beige" />
</Typography>
</section>
);
}
export default example;
What I've Tried / Fun Facts
No errors in the console.
Some colors may be preserved tailwind color names?
Tried changing color names in tailwind config
Tried changing hex values in tailwind config
Conclusion
Edit: Discovered an easier way:
<Icon name={faHandSpock} color="text-beige" /> // full classname
// remove partial className, pass in object
function Icon({ name, color, scale }) {
return (
<FontAwesomeIcon
icon={name}
className={color}
size={scale}
/>
);
}
export default Icon;
TailwindCSS doesn't allow you to generate classes dynamically. So when you use the following to generate the class…
className={`text-${color}`}
…TailwindCSS will not pick that up as a valid TailwindCSS class and therefore will not produce the necessary CSS.
Instead, you must include the full name of the class in your source code.
For this you can create any function which returns the required string like this:
function changeFAColor (color) {
if(color === dark) return "text-dark"
(color === white) return "text-white"
(color === secondary) return "text-secondary")
.
.
.
(color === purple) return "text-purple")
(color === yellow) return "text-yellow")
}
And use it in the component
<FontAwesomeIcon
icon={name}
className={`${changeFAcolor(color)}`}
size={scale}
/>
Tailwind generates a CSS file which contains only the classes that you've used in the project.
The problem you're experiencing is because Tailwind doesn't recognise the generated class you're applying in "FC: Icon Render". In particular, this line:
className={`text-${color}`}
To quote the documentation:
The most important implication of how Tailwind extracts class names is
that it will only find classes that exist as complete unbroken strings
in your source files.
If you use string interpolation or concatenate partial class names
together, Tailwind will not find them and therefore will not generate
the corresponding CSS:
https://tailwindcss.com/docs/content-configuration#class-detection-in-depth
To resolve your problem, either pass in the full class name instead of generating it or safelist all of your text-{color} classes in your config file.
Assign your colors to a variable:
const colors = {
dark: "#121212",
white: "#fff",
...
Pass them into your config for theme:
theme: {
colors,
. . .
Safelist your colors:
safelist: Object.keys(colors).map(color => `text-${color}`),

Mui v5 styleOverrides not working with themes

I am trying to style using theme overrides as laid out in the documentation here:
I have the following code sandbox:
import * as React from 'react';
import { ThemeProvider, createTheme } from '#mui/material/styles';
import Select from '#mui/material/Select'
import MenuItem from '#mui/material/MenuItem'
const theme = createTheme({
components: {
MuiSelect: {
styleOverrides: {
root: {
background: '#000',
},
},
},
},
});
export default function GlobalThemeOverride() {
return (
<ThemeProvider theme={theme}>
<Select
labelId="demo-simple-select-label"
id="demo-simple-select"
variant="standard"
>
<MenuItem value={10}>Ten</MenuItem>
<MenuItem value={20}>Twenty</MenuItem>
<MenuItem value={30}>Thirty</MenuItem>
</Select>
</ThemeProvider>
);
}
The Select box should have a background of #fff however no background is set at all. :(
This looks like a bug to me (or at least missing a feature that is reasonable for developers to expect to be there). The issue is that Select doesn't define any styles of its own at the root level, so it doesn't leverage the code (which would be a call to MUI's styled such as here for the select class) that would take care of looking at the theme and applying the corresponding style overrides. I recommend logging an issue.
There are a couple possible workarounds.
Workaround 1 - Target the select CSS class
This approach may work, but it depends on what all you are trying to do since this targets a child of the root element.
const theme = createTheme({
components: {
MuiSelect: {
styleOverrides: {
select: {
backgroundColor: "#000",
color: "#fff"
}
}
}
}
});
Workaround 2 - Target the MuiInput-root CSS class
The approach below targets the same element as MuiSelect-root by leveraging MuiInput-root (the rendering of the root element of the Select is delegated to the Input component when the variant is "standard") and then qualifying it via "&.MuiSelect-root" so that it only affects Select rather than all inputs.
const theme = createTheme({
components: {
MuiInput: {
styleOverrides: {
root: {
"&.MuiSelect-root": {
backgroundColor: "#000",
color: "#fff"
}
}
}
}
}
});

Emotion - pass style object to external library

I am using reactjs-popup, and one of it's props is contentStyle, which allow you to pass css-in-js object to style an internal div in the library.
however when I pass css object with #media in it, the library doesn't deal with it.
I wonder if there is a way to tell emotion to "translate" this object, or somehow wrap the library element, so it can treat the #media query as needed.
this is a code to demonstrate:
/** #jsx jsx */
import { jsx } from '#emotion/core';
import ReactJsPopup from 'reactjs-popup';
import { FC, PropsWithChildren } from 'react';
const Modal: FC<{}> = props => {
const style = {
padding: 0,
minHeight: '100%',
'#media (min-width: 576px)': {
minHeight: 'auto' // <----------- Doesn't work
}
}
return (
<ReactJsPopup contentStyle={style}>
{(close): JSX.Element => (
<div>
BODY
</div>
)}
</ReactJsPopup>
);
};
export default Modal;
Inline style objects currently do not support media queries.
The viable option here is to use the className prop to style the content. As the docs reads:
this class name will be merged with the component element: ex className='foo' means foo-arrow to style arrow, foo-overlay to style overlay and foo-content to style popup content
When using emotion, you can make sure that the selectors are unique using this property.
import { css } from "emotion";
<ReactJsPopup
className={css`
&-content {
color: red;
}
`}
>
</ReactJsPopup>
Note: The & is for the random classname that is going to be added by emotion. Followed by content that is added by the library

How do I pass complex styles (i.e. stylesheets) to React components as props?

I'm working on a large React project where each member of the team has been making components and stylesheets separately. I'm trying to find the common elements and re-write the code, creating re-usable components. At the moment each of these components has a stylesheet -- SCSS -- already written.
What I'd like to do is be able to pass styles to the component so that it can be customised (somewhat) in different locations. I know how to do this for the top-level HTML element in the component
export default class BoxWithSliderAndChevron extends Component {
render() {
const {
props: {
styles
},
} = this;
return (
<div className="BoxWithSliderAndChevron-main" style={styles}>
but as I understand it, these styles will only apply to this outer div? How can I pass styles such that I can re-style elements further down in the component's structure, using their classNames? As if I were passing a new stylesheet that would override the default stylesheet?
I suppose I could pass a number of style objects, but that seems cumbersome -- I'm wondering if there is a simpler way?
What you are trying to achieve kinda goes against the whole idea of inline styles (non-global, non-separated from implementation, etc), however you are right, passing a style prop and trying to apply it to a div will inmediatly result to only the parent having the styles applied.
One suggestion would be to merge the component styles with the props, ex:
import { StyleSheet } from 'react-native';
class Foo extends React.PureComponent {
render() {
return (
<div style={StyleSheet.merge([styles.parentStyle, styles.parentStyle])}>
<div style={StyleSheet.merge([styles.childStyle, styles.childStyle])}>
</div>
)
}
}
const styles = StyleSheet.create({
parentStyle: {
backgroundColor: 'red'
},
childStyle: {
backgroundColor: 'blue'
}
});
It is tedious work, but it is basically what you are trying to achieve, another approach is having theming globally applied:
import { StyleSheet } from 'react-native';
import { t } from '../theming'; // <- You switch themes on runtime
class Foo extends React.PureComponent {
render() {
return (
<div style={StyleSheet.merge([styles.parentStyle, t().parentStyle])}>
<div style={StyleSheet.merge([styles.childStyle, t().childStyle])}/>
</div>
)
}
}
const styles = StyleSheet.create({
parentStyle: {
backgroundColor: 'red'
},
childStyle: {
backgroundColor: 'blue'
}
});
/// Theming file would be something like:
// PSEUDO IMPLEMENTATION
import theme1 from 'theme1.json';
import theme2 from 'theme2.json';
availableThemes = {
theme1,
theme2
}
currentTheme = availableThemes.theme1
function setTheme(theme) {
currentTheme = availableThemes[theme]
}
export function t() {
return current theme
}

styled-system props typing with TypeScript

I'm using styled-system and one key of the library is to use the shorthand props to allow easy and fast theming.
I've simplified my component but here is the interesting part:
import React from 'react'
import styled from 'styled-components'
import { color, ColorProps } from 'styled-system'
const StyledDiv = styled('div')<ColorProps>`
${color}
`
const Text = ({ color }: ColorProps) => {
return <StyledDiv color={color} />
}
I have an error on the color prop which says:
Type 'string | (string | null)[] | undefined' is not assignable to
type 'string | (string & (string | null)[]) | undefined'.
I think that's because styled-system use the same naming as the native HTML attribute color and it conflicts.
How do I solve this?
color seems to be declared in react's declaration file under HTMLAttributes - it's not exported.
I had to work around this by creating a custom prop
Example is using #emotion/styled but also works with styled-components
// component.js
import styled from '#emotion/styled';
import { style, ResponsiveValue } from 'styled-system';
import CSS from 'csstype';
const textColor = style({
prop: 'textColor',
cssProperty: 'color',
key: 'colors'
});
type Props = {
textColor?: ResponsiveValue<CSS.ColorProperty>
}
const Box = styled.div<Props>`
${textColor};
`
export default Box;
// some-implementation.js
import Box from '.';
const Page = () => (
<Box textColor={['red', 'green']}>Content in a box</Box>
);
This seems to only happen when you pass the prop down from an ancestor/parent component to a custom component rather than directly to the "styled" component. I found a discussion about it in the styled-components GitHub issues. Following the thread from there there is discussion of utilising transient props and their ultimate inclusion in styled-components v5.1.
This however didn't seem to solve the problem completely in my case.
The problem appears to be due to the component in question returning an HTML div element and so it is extended correctly (by React.HTMLAttributes) to include color: string | undefined as a DOM attribute for that element. This is of course not compatible with ColorProps hence the error. Styled-components filters out a whitelist that includes color however this won't happen in your custom or HOC.
This can be resolved in a number of ways, but the cleanest seems to be adding as?: React.ElementType to your type definition.
In this case:
import React from 'react'
import styled from 'styled-components'
import { color, ColorProps } from 'styled-system'
interface Props extends ColorProps { as?: React.ElementType }
const StyledDiv = styled('div')<Props>`
${color}
`
const Text = ({ color }: Props) => {
return <StyledDiv color={color} />
}
This way the extension by React.HTMLAttributes is replaced by React.ElementType and so there is no longer a conflict with the color DOM attribute.
This also solves problems with passing SpaceProps.
NOTE:
It appears styled-system has been unceremoniously abandoned. There are a few open issues about what is being used to replace it. My recommendation after a little deliberation is system-ui/theme-ui. It seems to be the closest direct replacement and has a few contributors in common with styled-system.
Instead of using ColorProps, try using color: CSS.ColorProperty (`import * as CSS from 'csstype'); Here is a gist showing how I'm creating some a typed "Box" primitive with typescript/styled-system: https://gist.github.com/chiplay/d10435c0962ec62906319e12790104d1
Good luck!
What I did was to use Typescript cast capabilities and keep styled-system logic intact. e.g.:
const Heading: React.FC<ColorProps> = ({ color, children }) => {
return <HeadingContainer color={(color as any)} {...props}>{children}</HeadingContainer>;
};
Just to add to xuanlopez' answer - not sure what issue the 5.0.0 release specifically resolves - but using $color as the renamed prop rather than textColor designates it as a transient prop in styled components so as a prop it won't appear in the rendered DOM.
Building on Chris' answer, and using the latest docs on on custom props.
// core/constants/theme.ts
// Your globally configured theme file
export const theme = { colors: { primary: ['#0A43D2', '#04122B'] } }
// core/constants/styledSystem.ts
import {
color as ssColor,
ColorProps as SSColorProps,
TextColorProps,
compose,
system,
} from 'styled-system'
// Styled-system patch for the color prop fixing "Types of property 'color' are incompatible"
// when appling props to component that extend ColorProps.
export interface ColorProps extends Omit<SSColorProps, 'color'> {
textColor?: TextColorProps['color']
}
export const color = compose(
ssColor,
system({
// Alias color as textColor
textColor: {
property: 'color',
// This connects the property to your theme, so you can use the syntax shown below E.g "primary.0".
scale: 'colors'
}
})
)
// components/MyStyledComponent.ts
import { color, ColorProps } from 'core/constants/styledSystem.ts'
interface MyStyledComponentProps extends ColorProps {}
export const MyStyledComponent = styled.div<MyStyledComponentProps>`
${color}
`
// components/MyComponent.ts
export const MyComponent = () => <MyStyledComponent textColor="primary.0">...
EDIT: updating to styled-components ^5.0.0 fixes this
https://github.com/styled-components/styled-components/blob/master/CHANGELOG.md#v500---2020-01-13

Categories