Search code examples
javascriptreactjsstyled-components

Trouble with 'this' keyword in React styled components?


I am currently trying to work out using styled components, but I am having a hard time creating components like usual. More specifically, I am getting an error with the 'this' keyword, and passing properties.

In my main JavaScript file I try to create a component like this (normal to me):

let newStyledComponent = <HomePageDiv property1 = {property1} ... />

In HomePageDiv.js I have one constant that is the div, and one constant which is the keyframes that this div will animate:

import React from 'react';

import styled, { keyframes } from 'styled-components';

export const HomePageDiv = styled.div`
    height: 100vh;
    width: 100vw;
    display: flex;
    flex-direction: column;
    position: absolute;
    overflow: hidden;
    animation: ${backgroundChange} 4s ease-in-out 0s infinite;
`

const backgroundChange = keyframes`
    0%, 100% {
        background: radial-gradient(ellipse at ${this.props.xLeftPercent+`%`} ${this.props.yLeftPercent+'%'}, rgba(${this.leftR + this.leftRStep * 0}, ${this.leftG + this.leftGStep * 0}, ${this.leftB + this.leftBStep * 0}, 0.5), transparent),
                    radial-gradient(ellipse at ${this.props.xRightPercent+`%`} ${this.props.yRightPercent+'%'}, rgba(${this.rightR + this.rightRStep * 0}, ${this.rightG + this.rightGStep * 0}, ${this.rightB + this.rightBStep * 0}, 0.5), transparent);
    }

    ...

    99% {
        ...
    }
`

export default HomePageDiv;

Given this, why am I getting the error:

Uncaught TypeError: Cannot read property 'props' of undefined

And, similarly if I take away the 'this' keyword I would also get:

Uncaught ReferenceError: props is not defined

Solution

  • Styled components are written like a functional component, this implies that there is no this. What you can do is ${(props) => props.xLeftPercent}.