Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use this.props in React Styled Components

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

like image 562
FunnelScr Avatar asked Jun 11 '20 13:06

FunnelScr


1 Answers

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" />
    </>
  );
};

Edit affectionate-moon-netoi

enter image description here

like image 179
Dennis Vash Avatar answered Oct 23 '22 18:10

Dennis Vash