React: Why not just use a styles object instead of styled components?

I've already written apps that react natively and I'm 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 benefit from it, other than the fact that I can do media queries on style definitions in the same file as my component.

But let's 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 I write this in styled components? Is it just the case that I have certain styles dependent on certain ones props

that highlight the styled components?

For example, this doesn't work in react:

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

      

+3


source to share


2 answers


One early roadblock you will run into with clean inline styles is the lack of pseudo selectors :hover

, :active

etc. Also, as you mentioned, you cannot use media queries either.

The styled components are great. Also check out Aphrodite or Glamourous.



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

+2


source


If pseudo selectors are not needed, you can do something like this:

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

      



Styled Components is probably the best option. Also, look at Radium as another option. Manages pseudo selectors and media queries. Super easy to use.

+2


source







All Articles