Moshe
Moshe

Reputation: 7007

Multiple Prop Checks in Styled Components

I know that in styled-components, I can do a check for a prop like this:

${props => { if (props.size)...return...

However, from what I can tell if I want to do a second prop check, then I need to start all over again:

${props => { if (props.color)...return...

What I am wondering is if there is a way to do just one ${props... with different returns for different cases?

If so, any idea how?

Thanks.

Upvotes: 2

Views: 2835

Answers (3)

GollyJer
GollyJer

Reputation: 26772

You can simplify a little by accessing the props object up front. There's a little less repetition this way.

const StyledComponent = styled.div(
  (props) => `
    background-color: green;

    ${props.warn && `
      background-color: yellow;
    `}

    ${props.alert && `
      background-color: red;
    `}

  `
);

Upvotes: 3

Ted
Ted

Reputation: 14927

I prefer to keep my css separate, like in a styles.js file. Take the following code for example. It keeps the css organized, and makes implementing the different options pretty clean. Of course, add your css into the appropriate definitions

//styles.js
import { css } from 'styled-components';

export const buttonbase = css`/*base styles for all buttons*/`;
export const small = css`/*small size styles*/`;
export const medium = css`/*default size styles*/`;
export const large = css`/*large size styles*/`;
export const floating = css`/*float styles*/`;

And in your component file:

//Button.js
import React from 'react';
import PropTypes from 'prop-types';
import styled from 'styled-components';
import * as Styles from './styles';

const propTypes = {
  floating: PropTypes.bool,
  size: PropTypes.oneOf(['small', 'medium', 'large']),
  children: PropTypes.node,
};

const defaultProps = {
  floating: false,
  size: 'medium',
};

const ButtonBase = styled.button`
  ${Styles.buttonbase};
  ${props => (props.floating ? Styles.floating : '')};
  ${props => Styles[props.size]};
`;

const Button = ({ floating, size, children, ...rest }) => (
  <ButtonBase
    size={size}
    floating={floating}
    {...rest}
  >
    {children}
  </ButtonBase>
);

Button.propTypes = propTypes;
Button.defaultProps = defaultProps;

export default Button;

Upvotes: 2

Marwane Boudriga
Marwane Boudriga

Reputation: 191

Theres a package called styled-is that can help you do this in a clean and nice way.

Upvotes: 1

Related Questions