4
votes

I have written apps in react native before, and I am about to start my first react project. I noticed a tool called Styled Components: https://www.styled-components.com/docs/basics#motivation

However, I don't see any clear benefits of it except the fact that I can do media queries within the style definitions all within the same file as my component.

But lets say I have this button:

import React from 'react';

const StyledButton = ({ children }) => {
  return (
    <button type="button" style={styles.button}>
      { children }
    </button>
  );
}

const styles = {
  button: {
    backgroundColor: '#6BEEF6',
    borderRadius: '12px',
    border: 'none',
    boxShadow: '0 5px 40px 5px rgba(0,0,0,0.24)',
    color: 'white',
    cursor: 'pointer',
    fontSize: '15px',
    fontWeight: '300',
    height: '57px',
    width: '331px',
  }
}

export default StyledButton;

How would writing this in styled-components be much different? Is it only the case where I have certain styles that depend on certain props that styled-components shines?

Example, this doesn't work in react:

const StyledButton = ({ children, primary }) => {
  return (
    <button type="button" style={[styles.button, { color: primary ? 'green' : 'red' }]}>
      { children }
    </button>
  );
}
2
It doesn't work because the style attribute takes an object instead of an array. facebook.github.io/react/docs/dom-elements.html#styleJeroen Wienk
What would be the react way of doing something like that?bigpotato
You can merge your styles.button with the new object with style={Object.assign(styles.button, { color: primary ? 'green' : 'red' })}Jeroen Wienk

2 Answers

2
votes

One early roadblock you will run into with pure inline styles is the lack of pseudo-selectors:hover, :active etc. Also like you mentioned you can't use media queries either.

Styled Components is great. Also check out Aphrodite or Glamourous.

Here is a nice comparison of some of these librarys https://medium.com/seek-blog/a-unified-styling-language

2
votes

If pseudo-selectors aren't needed, you could do something like you've asked like this:

const StyledButton = ({ children, primary }) => {
  return (
    <button type="button" style={{ ...styles.button, color: primary ? 'green' : 'red' }}>
      { children }
    </button>
  );
}

Styled Components is probably a better option though. Also, take a look at Radium as another option. Handles pseudo-selectors and media queries too. Super easy to use.