Skip to content

Instantly share code, notes, and snippets.

@oziks
Created January 4, 2018 11:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save oziks/e6efc06de39ab9b8a5c177cfadc28d11 to your computer and use it in GitHub Desktop.
Save oziks/e6efc06de39ab9b8a5c177cfadc28d11 to your computer and use it in GitHub Desktop.
Build SVG Icon components with React (bicolor and fade state)
import { Component } from 'react';
import PropTypes from 'prop-types';
class IconComponent extends Component {
render() {
const { size, faded } = this.props;
const colors = {
primaryColor: faded ? '#dfdfe7' : '#00cc99',
secondaryColor: faded ? '#dfdfe7' : '#f5a623',
};
return this.renderSvgIcon({ ...colors, size });
}
}
IconComponent.defaultWidthSize = 32;
IconComponent.getDimensions = (width, height, size = IconComponent.defaultWidthSize) => ({
width: width >= height ? size : size / height * width,
height: height >= width ? size : size / width * height,
viewBox: `0 0 ${width} ${height}`,
});
IconComponent.defaultProps = {
faded: false,
size: IconComponent.defaultWidthSize,
};
IconComponent.propTypes = {
faded: PropTypes.bool,
size: PropTypes.number,
};
export default IconComponent;
import React from 'react';
import ReactDOM from 'react-dom';
import PictureIcon from './PictureIcon';
ReactDOM.render(
<PictureIcon faded size={128} />,
mountNode
);
import React from 'react';
import IconComponent from './IconComponent';
class PictureIcon extends IconComponent {
// eslint-disable-next-line class-methods-use-this
renderSvgIcon({ primaryColor, secondaryColor, size }) {
const dimensions = IconComponent.getDimensions(37, 37, size);
return (
<svg {...dimensions} xmlns="http://www.w3.org/2000/svg">
<g fill="none" fillRule="evenodd">
<g transform="translate(1 1)" strokeLinejoin="round" strokeWidth="2">
<path
stroke={secondaryColor}
d="M23.068 23.068l-4.773-11.932-3.977 8.75-3.977-4.772-4.773 7.954M.795 23.068h27.046"
/>
<circle stroke={secondaryColor} cx="7.955" cy="7.955" r="2.386" />
<path stroke={primaryColor} d="M.795.795H27.84V27.84H.795z" />
<path stroke={primaryColor} strokeLinecap="round" d="M31.035 10.152l3.17.288-2.169 23.765-23.765-2.169" />
</g>
<path d="M-1-1h38v38H-1z" />
</g>
</svg>
);
}
}
export default PictureIcon;
@CyrilKrylatov
Copy link

You should use a SVG optimizer like SVGOMG to remove what it seems to me useless groups (G tags) and that ugly transform="translate(1 1)". :3

@oziks
Copy link
Author

oziks commented Jan 4, 2018

@DaPo I use a svgo (npm cli package) also used by SVGOMG 😃.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment