Search code examples
reactjsstyled-components

Styled-component not taking props


I'm trying to pass props to my styled component. I am using the styled-component npm dependency.

import React, { Component } from 'react';
import styled from 'styled-components';

class WidgetContainer extends Component {

  render() {

    return (
        <Wrapper name='widget-container'>
        </Wrapper> 
    );
  }
}

const mapStateToProps = state => {
  return {
    user: state.user, 
    bannerStatus: true
  };
};

export default withRouter(connect(mapStateToProps)(WidgetContainer));

const Wrapper = styled.div`
  display: flex;
  flex-direction: column;
  width: 100%;
  min-height: 100vh;
  margin: auto;
  align-items: center; 
  justify-content: flex-start;
  background: -webkit-linear-gradient(top, rgba(162, 209, 234, 1) 0%, rgba(56, 83, 132, 1) 100%);
  padding-top: ${(props) => { 
    console.log(props.bannerStatus)
    console.log('DATA')
    return props.user ? '160px' : '126px'}};
  overflow-y: auto;
  padding-bottom: 40px;
  @media(max-width: 768px) {
    padding-top: 126px;
    padding-bottom: 5px;
  }
`;

The console.log you can see returns undefined. Even though the value is hard-coded. The ternary operator doesn't work as a result.

Here are the docs: https://www.styled-components.com/docs/basics#adapting-based-on-props.


Solution

  • You are mapping state to props in only the WidgetContainer. Your Wrapper component is not being passed any props.

    Try

    <Wrapper bannerStatus={props.bannerStatus} name='widget-container' />
    

    OR

    <Wrapper user={props.user} bannerStatus={props.bannerStatus} name='widget-container' />