I'm writing tests for components I have main component Icon
const Icon: React.FC<IIconPropTypes> = ({ size, color, icon, onClick, blockEvents }) => (
<IconWrapper onClick={onClick} blockEvents={blockEvents}>
<IconSvg color={color} hasClick={!!onClick} width={size}>
<path d={ICONS_PATH[icon]} />
</IconSvg>
</IconWrapper>
);
and IconSvg which I am testing
const IconSvg = styled.svg<IIconSvgProps>`
cursor: ${(props) => (props.hasClick ? 'pointer' : 'default')};
display: inline-block;
vertical-align: middle;
width: ${(props) => (props.width ? `${props.width}px` : '100%')};
path {
fill: ${(props) => (props.color ? props.color : '#edcd7d')};
transition: all 0.3s;
}
`;
This is how my test looks like
it('matches snapshot and renders without color prop', () => {
const [hasClick, width] = [true, 100];
const component = renderer.create(<IconSvg hasClick={hasClick} width={width}/>);
const tree = component.toJSON() as ReactTestRendererJSON;
expect(tree).toMatchSnapshot();
expect(component.root.findByType('path')).toHaveStyleRule('fill', '#edcd7d');
})
But findByType cannot find the path, and therefore the fill property, can anyone know what the error is and how to reach it?
You are testing your IconSvg component here:
let component = renderer.create(<IconSvg hasClick={hasClick} width={width}/>);
According to your code IconSvg is just a styled svg. You need to test Icon component which has a path element in it:
let component = renderer.create(<Icon size={} color={} icon={} onClick={} blockEvents={} } />);
Related
I'm working with styled-components in atomic system.
I have my <Atom title={title} onClick={onClick}/>
And I have molecule that extends that atom, by just adding some functionality to it without wrapping element:
const Molecule = ({}) => {
const [title, setTitle] = useState('Base title')
const onClick = () => {
// some actions
}
useEffect(()=>{
setTitle('New title')
},[conditions changed])
return(
<Atom title={title} onClick={onClick}/>
)
}
I have base styling in <Atom/> but I would like to add some more to it in <Molecule/>. Is it possible to do it without creating extra wrapper?
It is possible, but the question is if it's worthy the effort - the most anticipated way would be to do it as the documentation says - to wrap the styled component and extend the styles (but this is what you want to avoid). So either:
you could assign a className to Atom, so you can adjust/overwrite the styles with CSS
pass the extraStyles props to Atom and then pass to the styled component and just use inside after the previous, default styles to overwrite them
or either pass some extraStyles as CSSProperties object and just use them as inline styling.
https://codesandbox.io/s/withered-leftpad-znip6b?file=/src/App.js:64-545
/* styles.css */
.extraClass {
color: green;
}
const AtomStyled = styled.div`
font-size: 17px;
color: blue;
font-weight: 600;
`;
const Atom = ({ children, className, extraStyles }) => {
return (
<AtomStyled style={extraStyles} className={className}>
{children}
</AtomStyled>
);
};
const Molecule = () => {
return (
<Atom className={'extraClass'} extraStyles={{ fontSize: 27 }}>
Atom
</Atom>
);
};
In the old way material ui (version 4 and earlier) styled components you could use className property to "Select" which styles are active, ie a component could be styled like:
const styles = (theme: ThemeTy) => ({
root: {
width: '100%',
},
rootLight: {
color: theme.palette.getContrastText(theme.palette.primary.main),
},
})
const useStyles = makeStyles(styles);
function MyComp() {
const classes = useLocalStyles();
return <Input
className=classNames(classes.root, highContrast ? classes.rootLight : undefined)}
value={100}
/>
}
However in the new api one would define the classes outside the component similar to styled-components does it:
const StyledInput = styled(Input)(({theme}) => `
width: '100%',
`);
function MyComp() {
return <StyledInput
value={100}
/>
}
However how would I add the conditional styling? Would I have to use the sx element? And thus use conditional styling everywhere?
You can pass any props to your StyledInput and then style the component based on them:
const StyledInput = styled(Input)(({ theme, showborders }) => ({
width: "100%",
border: showborders ? "3px solid red" : "none"
}));
...
const [showBorders, setShowBorders] = React.useState(false);
return (
<Box>
<StyledInput showBorders={showborders ? 1 : 0} value={100} />
</Box>
);
Demo
I am unsure if this is a me issue or the libary or just not possible in general (although it should).
What I am trying to do is the following:
I have used Material UI to create a "Libary" that I can reuse in all my projects so I do not have to do all the things every time that I usually do. I have used styled components to style some of the material ui components such as Button and TextField. I have exposed some of those modified properties to the app that consumes my libary. When these styles that are exposed are generic everything works fine.
As an example here is my modified Button with just basic styles:
const StyledButton = styled(Button)`
width: ${props => props.width || "265px"};
height: ${props => props.height || "40px"};
margin: ${props => props.margin} !important;
padding: ${props => props.padding};
font-weight: ${props => props.fontWeight || "700"};
text-decoration: ${props => props.textDecoration};
`
This button then is used in the libaries Button component thus masking the material ui part of it like so:
const MyButton = (props) => {
return (<StyledButton width={props.width} height={props.height} .../>)
}
And so forth. This is working. My issue arrises when I am trying to make the button change on some mobile breakpoint.
This is my full button component here:
const StyledButton = styled(Button)`
width: ${props => props.width || "265px"};
height: ${props => props.height || "40px"};
margin: ${props => props.margin} !important;
padding: ${props => props.padding};
font-weight: ${props => props.fontWeight || "700"};
text-decoration: ${props => props.textDecoration};
#media only screen and (max-width: ${MOBILE_BREAKPOINT}) {
width: ${props => props.mWidth || "165px"};
height: ${props => props.mHeight || "40px"};
margin: ${props => props.mMargin};
padding: ${props => props.mPadding};
font-weight: ${props => props.mFontWeight};
text-decoration: ${props => props.mTextDecoration};
}
`;
However when I am trying to now set these values I get errors in the console from React (as expected) that are not hindering the execution of my code. But still nothing is happening when I decrease screen width below 450px (MOBILE_BREAKPOINT).
The way I am trying to do it is by deconstructing the props js const {mWidth, mHeight} = mobile;
The values show up in the props of the component but they are not used. I am passing them like this:
<MyButton width={"75%"} height={"40px"} mobile={{mWidth: "95%}}/>
It just does not do what I want it to when the breakpoint is passed. The width stays at 75%. 95% is never activated.
Can anyone tell me what I am doing wrong or if this is impossible to achieve?
I appreaciate the help!
You can simply write your MyButton code like this:
const MyButton = (props) => {
const { width, height, mobile: {mWidth, mHeight}} = props;
return (
<StyledButton
width={width}
height={height}
mWidth={mWidth}
mHeight={mHeight}
/>
);
}
And then your media query worked fine.
I recommend you to set default value in destructuring part in the MyButton instead of in the StyledButton, in order to do that you can change MyButton component like this:
const MyButton = (props) => {
const {
width = "265px",
height = "40px",
mobile: {mWidth = "165px", mHeight = "40px"}
} = props;
return (
<StyledButton
width={width}
height={height}
mWidth={mWidth}
mHeight={mHeight}
/>
);
}
and then StyledButton should change like this:
const StyledButton = styled(Button)`
width: ${props => props.width};
height: ${props => props.height};
#media only screen and (max-width: ${MOBILE_BREAKPOINT}) {
width: ${props => props.mWidth};
height: ${props => props.mHeight};
}
`;
and you also can refactor StyledButton like below:
const StyledButton = styled(Button)`
width: ${({ width }) => width};
height: ${({ height }) => height};
#media only screen and (max-width: ${MOBILE_BREAKPOINT}) {
width: ${({ mWidth })=> mWidth};
height: ${({ mHeight })=> mHeight};
}
`;
I have the following svg component where I am passing props.
import React from 'react';
export default (props) => (
<svg {...props}>
<path
d="M11.5 16.45l6.364-6.364"
fillRule="evenodd"
/>
</svg>
);
I then have a styled-component that looks like this.
const Icon = styled(_Icon)`
${props =>
props.isActive &&
css`
transform: rotate(-180deg);
`};
`;
I am seeing the following react error.
Warning: React does not recognize the isActive prop on a DOM element.
I ran into the same issue with styled-components and I ended up doing something like this:
<Icon isactive={isActive.toString()} />
${props =>
props.isactive === 'true' &&
css`
transform: rotate(-180deg);
`};
}
const StyledIcon = styled(({ isActive, ...props }) => <Icon {...props} />)`
${props =>
props.isActive &&
css`
transform: rotate(-180deg);
`};
`
Is the much less hacky solution that also prevents the property from being unnecessarily rendered to the DOM
I had a similar issue and fixed the error by passing the props into a Styled Component instead of a normal html element. For you, you would change the svg element to something like this:
import React from 'react';
export default (props) => (
<SvgStyledComp {...props}>
<path d="M11.5 16.45l6.364-6.364" fillRule="evenodd"/>
</SvgStyledComp>
);
const SvgStyledComp = styled.svg`
${props => props.isActive && css`
transform: rotate(-180deg);
`};
`;
You can use transient-props.
here is tsx example :
Button is antd Button
import { Button } from 'antd';
import styled from 'styled-components';
interface IMyButtonProps {
$switchShape: boolean;
$myColor: string;
$myBorderColor: string;
}
let MyButton = styled(Button).attrs<IMyButtonProps>((props) => {
// console.log(props);
let myShape = props.$switchShape ? 'circle' : 'round';
return { type: 'primary', shape: myShape };
})<IMyButtonProps>`
margin-left: 10px;
${{
padding: '100px',
}}
${(props) => {
// You can get the result of Attrs
// console.log(props);
return `
color:${props.$myColor}
`;
}};
${(props) => {
// CSSProperties
return {
borderColor: props.$myBorderColor,
};
}};
`;
ghost is antd Button attr
<MyButton ghost={true} $switchShape $myBorderColor='black' $myColor='red'>
click me
</MyButton>
Simple way to fix this error is change props name to '$ + props_name'
Example:
interface MenuItemProps extends TypographyProps {
$isActive?: boolean;
}
I just read in the styled-components documentation that the following is wrong and it will affect render times. If that is the case, how can I refactor the code and use the required props to create a dynamic style?
Thank you in advance.
Tab component
import React from 'react'
import styled from 'styled-components'
const Tab = ({ onClick, isSelected, children }) => {
const TabWrapper = styled.li`
display: flex;
align-items: center;
justify-content: center;
padding: 100px;
margin: 1px;
font-size: 3em;
color: ${props => (isSelected ? `white` : `black`)};
background-color: ${props => (isSelected ? `black` : `#C4C4C4`)};
cursor: ${props => (isSelected ? 'default' : `pointer`)};
`
return <TabWrapper onClick={onClick}>{children}</TabWrapper>
}
export default Tab
I believe what the documentation is saying is that you should avoid including your styles inside of the rendering component:
DO THIS
const StyledWrapper = styled.div`
/* ... */
`
const Wrapper = ({ message }) => {
return <StyledWrapper>{message}</StyledWrapper>
}
INSTEAD OF THIS
const Wrapper = ({ message }) => {
// WARNING: THIS IS VERY VERY BAD AND SLOW, DO NOT DO THIS!!!
const StyledWrapper = styled.div`
/* ... */
`
return <StyledWrapper>{message}</StyledWrapper>
}
Because what happens is when the component's Props changes, then the component will re-render and the style will regenerate. Therefore it makes sense to keep it separate.
So if you read further on to the Adapting based on props section, they explain this:
const Button = styled.button`
/* Adapt the colours based on primary prop */
background: ${props => props.primary ? "palevioletred" : "white"};
color: ${props => props.primary ? "white" : "palevioletred"};
font-size: 1em;
margin: 1em;
padding: 0.25em 1em;
border: 2px solid palevioletred;
border-radius: 3px;
`;
// class X extends React.Component {
// ...
render(
<div>
<Button>Normal</Button>
<Button primary>Primary</Button>
</div>
);
// }
this works because when you use the Button component in class X, it will know the props of class X without you having to tell it anything.
For your scenario, I imagine the solution would be simply:
const TabWrapper = styled.li`
display: flex;
align-items: center;
justify-content: center;
padding: 100px;
margin: 1px;
font-size: 3em;
color: ${props => (props.isSelected ? `white` : `black`)};
background-color: ${props => (props.isSelected ? `black` : `#C4C4C4`)};
cursor: ${props => (props.isSelected ? 'default' : `pointer`)};
`;
const Tab = ({ onClick, isSelected, children }) => {
return <TabWrapper onClick={onClick}>{children}</TabWrapper>
}
const X = <Tab onClick={() => console.log('clicked')} isSelected>Some Children</Tab>
I haven't tested this at all, so please feel free to try it out and let me know if it works for you or whatever worked for you!
You can pass an argument with Typescript as follows:
<StyledPaper open={open} />
...
const StyledPaper = styled(Paper)<{ open: boolean }>`
top: ${p => (p.open ? 0 : 100)}%;
`;
Another way to do it would be
const StyledDiv = styled.div.attrs((props: {color: string}) => props)`
width: 100%;
height: 100%;
background-color: ${(props) => props.color};
`
//...
render() {
return (
<StyledDiv color="black">content...</StyledDiv>
);
}
This way you are type-safe in terms of the props you want to send into the styled component. (Good when coding in Typescript)
For a more simple example with functional components:
Suppose you have an arrow like polygon and you need 2 of them pointing in different directions. So you can pass the rotate value by props
<Arrow rotates='none'/>
<Arrow rotates='180deg'/>
Then in the Component Arrow you have to pass the props like normal component to the styled component but in the styled component you have to use it like props:
import React from 'react';
import styled from "#emotion/styled";
const ArrowStyled = styled.div`
background-color: rgba(255,255,255,0.9);
width: 24px;
height: 30px;
clip-path: polygon(56% 40%,40% 50%,55% 63%,55% 93%,0% 50%,56% 9%);
transform: rotate(${props => props.rotates});
`
const Arrow = ({rotates}) => {
return (
<ArrowStyled rotates={rotates}/>
);
}
export default Arrow;
If you're using Typescript create an interface inside your styles file!
Otherwise, you won't be able to access props in your CSS
import styled from 'styled-components'
interface StyledLiProps{
selected: boolean
}
export const TabWrapper = styled.li`
// styles ...
color: ${props => (selected ? `white` : `black`)};
background-color: ${props => (selected ? `black` : `#C4C4C4`)};
`
And don`t forget to declare the props you want to use in your CSS inside your JSX
interface TabProps{
text: string;
}
const Tab = ({ text }: TabProps) => {
//...
return <TabWrapper selected={isSelected} onClick={() => updateTab}>{text}</TabWrapper>
}
Consider styled components documentation gives example of using reacts context api [2] for different themes.
[1] https://www.styled-components.com/docs/advanced
[2] https://reactjs.org/docs/context.html
Exporting styled-component
Button
and passing scrollPosition as a prop in functional component
PassingPropsToSyledComponent
import styledComponents from "styled-components";
export const Button = styledComponents.div`
position: ${ props => props.scrollPosition ? 'relative' : 'static' };
`;
export const PassingPropsToSyledComponent = ()=> {
return(
<Button scrollPosition={scrollPosition}>
Your Text Here
</Button>
)
}