I am trying to style my component using props
likes this:
const MyStyledComponent = styled.div`
position: fixed;
top: ${this.props.style.top};
left: ${this.props.style.left};
width: ${this.props.style.width};
height: ${this.props.style.height};
`;
But I am getting the following error:
Uncaught TypeError: Cannot read property 'props' of undefined
You need to use a callback which accepts props
passed to the component like so:
const MyStyledComponent = styled.div`
position: fixed;
top: ${(props) => props.top};
`;
<MyStyledComponent top={5} />;
See Getting Started in docs.
Bonus: typically when working with css-in-js
(like styled-component
), there are many handy tools that used alongside, like styled-tools
.
import styled, { createGlobalStyle } from "styled-components";
import { prop } from "styled-tools";
const GlobalStyle = createGlobalStyle`
body {
margin: 0;
padding: 5px;
border: 5px solid pink;
}
`;
const Box = styled.div`
height: ${({ height }) => height}px;
width: ${({ width }) => width}px;
background-color: ${({ color }) => color};
`;
const Box2 = styled.div`
${({ height, width, color }) => ({
height,
width,
"background-color": color
})}
`;
const Box3 = styled.div`
height: ${prop("height")}px;
width: ${prop("width")}px;
background-color: ${prop("color")};
`;
const N = 100;
const App = () => {
return (
<>
<GlobalStyle />
<Box width={N} height={N} color="palevioletred" />
<Box2 width={N * 1.5} height={N * 1.5} color="black" />
<Box3 width={N * 2} height={N * 2} color="palegoldenrod" />
</>
);
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With