DEV Community

Discussion on: You Don't Need CSS-in-JS: Why I Use Stylesheets

Collapse
pozda profile image
Ivan Pozderac

Every code can be spaghetti. What horrible SASS and Stylus files have I seen last couple of years and refactored to be smaller, readable and dry!

Don't get me wrong, I love using BEM and SASS, but styled components is something that actually removes visual noise and help me concentrate at one thing at the time as well as making process of sharing components between different suite of apps a little bit less difficult.

There are many ways to arrange your code and if you use defaults like writing css in the same file as component it could be distracting and overwhelming. I like to extract styles in separate file and just import what I need. So the example of simple searchbar component would be something like this:

import React from 'react'
import appConstants from 'utils/appConstants'
import {
    StyledSearchbar,
    StyledSearchbarField,
    StyledSearchbarIconWrapper
} from './SearchbarStyles'
import {Icon} from 'components'

interface Props {
    onChange: (e: React.ChangeEvent<HTMLInputElement>) => void,
    handleEnterKey: (e: React.KeyboardEvent<HTMLInputElement>) => void,
    onClick: () => void,
    query: string
}

const Searchbar = ({onChange, onClick, query, handleEnterKey}: Props) => (
    <StyledSearchbar>
        <StyledSearchbarField
            placeholder={appConstants.placeholder.SEARCH}
            onChange={onChange}
            onKeyDown={handleEnterKey}
        />
        <StyledSearchbarIconWrapper disabled={query.length < 1} onClick={query.length < 1 ? undefined : onClick}>
            <Icon d={Icon.res.SEARCH} height={16} width={16} />
        </StyledSearchbarIconWrapper>
    </StyledSearchbar>
)
export default Searchbar

And all the styles are separated and working fine from the other file. If you need to change CSS, no need to medle with component files.

And the other thing is that we have few apps with components that we share between them and this helps a lot, not that you can't do it with SASS or PostCSS, but we estimated that styled components will be less painful for that kind of job.