I am passing props from one stateless function to another, and I get a reference error saying the prop is undefined. Here is the parent function:
const Home = () => {
return (
<App>
<BackgroundImage url="mercedes-car.jpg">
<h1>Test</h1>
</BackgroundImage>
</App>
)
}
And here is the BackgroundImage function:
const Image = styled.div`
background-image: ${props => url(props.imageUrl)};
background-size: cover;
height: 100%;
width: 100%;
`;
const BackgroundImage = (props) => {
console.log(props)
return (
<Image imageUrl={ props.url }>
{ props.children }
</Image>
)
}
The error is that url is undefined; however, when I console.log(props), I get an object with url and children. Any direction or explanation as to why this error is throwing would be appreciated!
I'm guessing you meant
background-image: ${props => url(props.imageUrl)};
to be
background-image: url(${props => props.imageUrl});
since the result of that function needs to be a string. Otherwise you're trying to call a function called url.
you have a scope issue. change it to:
const BackgroundImage = (props) => {
console.log(props)
const Image = styled.div`
background-image: url(${props.url});
background-size: cover;
height: 100%;
width: 100%;
`;
return (
<Image>
{ props.children }
</Image>
)
}
basically the props are not available to your image, because styled.div is not a normal react component that has props.
Another way is to leave your code as is but set the background image from inside the return function:(and remove it from the styled.div)
return (
<Image style={{backgroundImage: `url(${props.url})`}}>
{ props.children }
</Image>
)
}
Related
I am trying to create a button component using styled components that takes a prop as which can be a ComponentType | string When I try another prop called skin or size I get the error No overload matches this call. I have googled what I can think of under the sun. I have tried everything I could. I initially didn't use the attrs in styled components but after googling for hours I think I need to use it but not sure. What am I missing?
Here is the Button component:
const Button: FunctionComponent<FullProps> = ({
as,
children,
skin = "primary",
size = "medium",
...props,
}) => {
return (
<Component
as={as}
size={size}
skin={skin}
{...props}
>
{children}
</Component>
);
};
Here is the type FullProps which has all of the props but I'm trying reduce it to the smallest issue:
export type FullProps = {
as?: ComponentType | string;
isFullWidth?: boolean;
disabled?: boolean;
shadow?: ShadowStep;
size?: Size;
skin?: Skin;
theme?: Theme;
type?: HtmlButtonType;
href?: string;
onClick?: () => void;
children?: ReactNode;
id?: string;
loadingConfig?: LoadingConfig;
icon?: IconConfig;
};
I know when using styled components you should use the prop forwardedAs to pass a as value down. That part works if I just have a simple component that takes as:
const DemoALink = styled(Button)`
color: white;
background: #fb6058;
height: 4rem;
width: 100%;
display: flex;
justify-content: center;
align-items: center;
`;
Here is the styled component being used:
<DemoALink forwardedAs="a" skin="primary">
Testings
</DemoALink>
And this is the styling for the component:
export const Button = styled.button.attrs<FullProps>(
({ disabled, as, type }: FullProps) => ({
type: as === "button" && type ? type : undefined,
disabled,
})
// )<Required<FullProps> & { children: ReactNode }>`
)<Required<FullProps> & { children: ReactNode }>`
${baseStyles};
${({ skin, theme }) => getVariant({ skin, theme })}
padding-top: ${getHeight};
padding-bottom: ${getHeight};
box-shadow: ${shadow};
width: ${({ isFullWidth }: { isFullWidth: boolean }) =>
isFullWidth ? "100%" : "auto"};
`;
I recently ran into this same error while trying to use typescript in styled components. I eventually resolved it and found out the reason I was having that error. I'll sight an example for context.
imagine declaring a type for an avatar component like so:
interface Avatar {
src?: string,
alt: string,
height: string,
width: string,
}
It would be safe to make use of this type declaration in the desired component like so:
const AvatarContainer: FC<Avatar> = ({src, alt, width, height}) => {
return (
<Container width={width} height={height}>
<img src={src} alt={alt} />
</Container>
)
};
export default AvatarContainer;
const Container = styled.div<{width: string, height: string}>`
width: ${(props) => props.width || '35px'};
height: ${(props) => props.height || '35px'};
overflow: hidden;
border-radius: 50%;
`;
Note that the above will work correctly without erroring out. However, to reproduce the
no overload matches this call
error, let's modify the above jsx to:
const AvatarContainer: FC<Avatar> = ({src, alt, width, height}) => {
return (
<Container width={width} height={height}>
<img src={src} alt={alt} />
</Container>
)
};
export default AvatarContainer;
const Container = styled.div<Avatar>`
width: ${(props) => props.width || '35px'};
height: ${(props) => props.height || '35px'};
overflow: hidden;
border-radius: 50%;
`;
The above will error out. This is because the type definition 'Avatar' contains two more props, src and alt that our Container component does not need. What we want to do instead, is specify explicitly the props that our Container component needs as outlined in our first code example.
I hope this was helpful.
Here is how I resolved a No overload matches this call error in my styled-component:
interface Props{
someProp: string
}
const SomeStyledComponent = styled.div<{ someProp: string}>`
some-css-property: ${(props) => props.someProp}
`
export default function SomeCompnent({ someProp }: Props): ReactElement{
return(
<SomeStyledComponent someProp={someProp} />
)
}
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={} } />);
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};
}
`;
What is the better way to pass a component in props? And how it's better to call it as Component or as a function. Or there are no differences?
const HeaderComponet = props => {
return <div style={styles.header}>Header</div>;
};
const renderCardBody = props => {
return <div style={styles.body}>Body</div>;
};
function App() {
return (
<Card HeaderComponet={HeaderComponet} renderCardBody={renderCardBody} />
);
}
const Card = props => {
const { HeaderComponet, renderCardBody } = props;
return (
<div>
<p>Card</p>
{HeaderComponet && <HeaderComponet {...props} />}
{renderCardBody && renderCardBody(props)}
</div>
);
};
codesandbox https://codesandbox.io/s/hungry-violet-jlvsp
I would simply render it as Child Component
<Card>
<HeaderComponent {...props}/>
<RenderCardBody {...props}/>
</Card>
how it's better to call it as Component or as a function
In theory, both are same. JSX we write is converted to a function based JS and is used in that way.
Sample:
Class Component used as function
Function Component as a component
So which to use?
Function: If there is a processing involved. Say based on 1 state, it should show banner. On another, a form. Yes, the logic can be moved to another component as used, however, if a component needs to be smart and do processing based on state, such processing should be done in a function
Component: If its directly consumed. Like an form component wrapping multiple component to create a structure.
What is the better way to pass a component in props?
In my POV, you should not pass components as props. A component should know what its consuming. Still if you want to have dynamic component, I'd do in following manner.
Create a list of possible components that can be used and based on that create a map.
Create props getter function so you can dynamically use it.
Now based on props, get the component and props, and do rendering.
Sample:
What is the better way to pass a component in props?
Note: The Tile components are just for demo and hence they are very basic. In reality, they can be more complicated
const DefaultTile = (props) => Array.from({ length: props.count }, (_, i) => <div className='tile medium-tile' key={i}>Tile</div>)
const LargeTile = (props) => Array.from({ length: props.count }, (_, i) => <div className='tile large-tile' key={i}>Tile</div>)
const SmallTile = (props) => Array.from({ length: props.count }, (_, i) => <div className='tile small-tile' key={i}>Tile</div>)
const componentMap = {
large: LargeTile,
medium: DefaultTile,
small: SmallTile
}
const renderPropMap = {
large: (props) => ({ count: props.count, showExtraInfo: props.info }),
medium: (props) => ({ count: props.count }),
small: (props) => ({ count: props.count, onHover: props.onHover })
}
const App = (props) => {
const Comp = componentMap[props.size];
const childProps = renderPropMap[props.size](props)
return <Comp { ...childProps } />
}
ReactDOM.render(<App size='medium' />, document.querySelector("#app"))
.tile {
border: 1px solid gray;
display: inline-block;
margin: 4px;
}
.small-tile {
width: 50px;
height: 50px;
}
.medium-tile {
width: 100px;
height: 100px;
}
.large-tile {
width: 200px;
height: 200px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="app"></div>
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>
)
}