Search code examples
javascriptnode.jsreactjsstyled-componentsreact-props

React.js child component not updating styling derived from props, why? (styled-components)


I am new to react.js and I am trying to get my head around conditional styling depending on props passed down from parent components.

I'm trying to make a button that has styling differences depending on whether the 'disabled' prop is true or false. If the button is disabled (true) it should appear grey, otherwise, it's blue.

This is the code I have so far, although it is not working and I'm not sure why.

Parent component

import React from 'react';

import { storiesOf } from '@storybook/react';
import { action } from '@storybook/addon-actions';
import { linkTo } from '@storybook/addon-links';

import { Welcome } from '@storybook/react/demo';
// Buttons
import Primary from '../components/ButtonPrimary'

storiesOf('Welcome', module).add('to Storybook', () => <Welcome showApp={linkTo('Button')} />);

storiesOf('Buttons')
    .add('Primary', () => <Primary label="Default" disabled="false"></Primary>)

Child component

import React from "react";
import styled from 'styled-components';

const Button = styled.button`
    background-color: ${props => props.disabled ? '#EDEDED' : '#0076C0'};
    border: ${props => props.disabled ? '1px solid #DADADA' : 'none'};    
    color: ${props => props.disabled ? '#818181' : '#FFFFFF'};
    cursor: ${props => props.disabled ? 'unset' : 'pointer'};
    border-radius: 2px;
    font-family: Roboto-Regular;
    font-size: 16px;
    padding: 6px 32px;
    font-family: roboto, helvetica, sans-serif;
    font-size: 18px;

    &:focus {
        outline: none;
    }

    &:hover {
        box-shadow: ${props => props.disabled ? 'unset' : '0px 1px 2px 1px #b3b3b3'};
    }

    &:active {
        box-shadow: ${props => props.disabled ? 'unset' : 'inset 0 0 10px #2f2f2f80'};
    }
`;

export default class ButtonPrimary extends React.Component {
    render() {
        return (
            <div>
                <Button disabled={this.props.disabled}>{this.props.label}</Button>
            </div>
        )
    }
}

Does anyone have any idea why?


Solution

  • In your parent component, you need to change disabled to be a boolean instead of a string.

    storiesOf('Buttons')
        .add('Primary', () => <Primary label="Default" disabled={false} ></Primary>)
    

    Or in case if you need to use it as a string you need to specify your conditional

    ${props => props.disabled === 'true' ? '#EDEDED' : '#0076C0'};