Although ReactJS favours an inline approach to styling components there are advantages in using CSS.  This article does not advocate whether you should choose to use CSS or in-line styles in your react components, but if you decide to use CSS here are some tips for you.

* When using CSS with React components it is good to apply a parent class to the component then target everything inside the component relative to this parent class. This helps maintain the componentized nature of ReactJS. This tip is applicable whether you use React or not. Many times when dealing with other designers code we come across a situation where the designer applies a style across a broad selector which must then be overridden a number of times across the project. e.g.

BAD

<style>.message { background:red }</style>
<div class="my-widget">
 <span class="message">Now I have to override every message tag I use because you did not target this properly</span>
</div>

GOOD

<style>
 .my-widget > .message { background:green }
</style>
<div class="my-widget">
 <span class="message">I know this formatting will only apply to my widget</span>
</div>

If you do intend to use a class name across components make the class name long so there is less chance of conflicts across different projects. i.e ‘my-widgets-message’ would have been better than ‘message’

* Target your selectors as specific as possible to prevent leakage to child components. e.g.

BAD

<style>
 .my-widget button { background: blue }
</style>
<div class="my-widget">
 <button>I am blue</button>
 <div>
   <button>But I will also be blue and I don't want to be</button>
 </div>
</div>

GOOD

<style>
 .my-widget > button { background: blue }
</style>
<div class="my-widget">
 <button>I am blue</button>
 <div>
 <button>But I won't be blue</button>
 </div>
</div>

* Keep your CSS with your components. In traditional web design all javascript files normally go into a JS folder and all style sheets normally go into a CSS folder. However, if you remove components in ReactJS you might forget to remove the associated CSS file if it was in a separate location. This will eventually cause bloat over time as people who maintain your work might not know if a file is needed or not.  Each component should be placed in it’s own folder. If not in the same folder, the CSS file should be named appropriately. e.g MyComponent.jsx would have a CSS file of MyComponent.css in the same location.

* If you do not use CSS it is also good practice to keep your styles separate to your code. Common styles can then be imported into different components.

Give it a go Are you already following these suggestions?  If not why?