The React Styling Problem

Jamie Kyle
Jan 29, 2016 · 1 min read

The React community hasn’t come to an agreement on how to style components– split between using classnames or inline styles.

This becomes a problem when it comes to authoring components for the entire community. How do you write your component so that your users can style it however they want?

The answer is composition.

Write your base component with no styles, no classnames, and allow both of them to be specified manually. Then expose this base component to your users and they’ll be able to wrap your component styling it however they want.

function BaseComponent(props) {
return <div className={props.className} style={props.style}/>;
}
function ClassNameComponent() {
return <BaseComponent className="my-component"/>;
}
function InlineStyleComponent() {
return <BaseComponent style={{ display: "block" }}/>;
}

If you want to also provide a more opinionated component that works out of the box, you use this same pattern of composition.

If you do this, you’ll never have to worry about this style problem again.

Follow me on twitter

PS: I also wrote a tiny little library that can help your component accept classNames or inline styles (along with validating PropTypes). See it here.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch

Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore

Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store