danawoodman / react-fontawesome

A React Font Awesome component.
https://www.npmjs.com/package/react-fontawesome
MIT License
667 stars 72 forks source link

Add option to pass FontAwesome as css module #21

Closed callumsmits closed 8 years ago

callumsmits commented 8 years ago

react-fontawesome requires FontAwesome CSS to be included elsewhere in the project. I am working on a project that uses CSS modules and have included FontAwesome as a module. This commit adds a prop called cssModule, which is used to look up the FontAwesome css within the object, if passed. Otherwise API and usage are identical.

Also included are two extra tests that replicate the current tests, but supplying CSS class names using the cssModule prop.

danawoodman commented 8 years ago

@callumsmits thanks for this PR! To be honest, I'm not familiar with this approach or the problem it solves. Could you possibly explain a bit more why this is necessary? Thanks!

callumsmits commented 8 years ago

@danawoodman, sure, CSS modules allows modular and reusable CSS - see CSS Modules or What are CSS Modules and why do we need them? for a more in-depth explanation. I think additionally the philosophy fits well with React.

In my code I import the FontAwesome CSS as you would javascript and the object then has keys for each style in the CSS file. Your build system (webpack in my case) makes the CSS scope local by ensuring unique names. As an example:

import React, { PropTypes } from 'react';
import FontAwesome from 'react-fontawesome';
import faStyles from 'font-awesome/css/font-awesome.css';

const test = () => {
  const spanClass=`${faStyles.fa} ${faStyles['fa-rocket']}`;

  return (
    <span className={spanClass} />
  );
};

When you look at something like this in the browser you see:

<span class="font-awesome__fa___2otTb font-awesome__fa-rocket___lfSov"></span>

Because the class names are not the static names in the css file react-fontawesome doesn't work. However, with this commit you can do this:

const test = () => {
  return (
    <FontAwesome name="rocket" cssModule={faStyles} />
  );
};

and it works :). Of course if you leave out the cssModule prop, it functions exactly as before.

callumsmits commented 8 years ago

@danawoodman I just made a small tweak to improve flexibility - if the cssModule prop is passed, the className prop will still be added to className as a string rather than how I had it before, which was using it as a key for the cssModule object.

danawoodman commented 8 years ago

@callumsmits sorry for delay, I was gone all last week. I'll check this out shortly!

callumsmits commented 8 years ago

@danawoodman great thanks! I look forward to getting your feedback.

danawoodman commented 8 years ago

Sorry again for delay @callumsmits, merged! I will cut a new release here shortly

danawoodman commented 7 years ago

Published in version v1.2.0