6 October 2018

Styled components are the best way to give some visual aid to your components. The heavy lifting should be done by a library, it can be either material design, bootstrap, semantic, etc... To adjust things or create custom components, you can use styled components. This gives the ability to keep your styles where your components are. The files structure is clean and the styles are not scattered around. This adds the simplicity desperately needed in the styling world.

Standard HTML elements

Source code viewer
  1. import styled from 'styled-components';
  2.  
  3. const LoadMoreButtonWrapper = styled.div`
  4. text-align: center;
  5. `;
  6.  
  7. export class MyClass extends PureComponent {
  8. render() {
  9. return (
  10. <LoadMoreButtonWrapper>
  11. ...
  12. </LoadMoreButtonWrapper>
  13. );
  14. }
  15. }
Programming Language: ECMAScript

Existing ES6 components

Source code viewer
  1. import styled from 'styled-components';
  2. import Dimmer from 'semantic-ui-react/dist/commonjs/modules/Dimmer';
  3.  
  4. const Item = styled(Dimmer.Dimmable)`
  5. height: 300px;
  6. width: 200px;
  7. `;
  8.  
  9. <Item
  10. as={Image}
  11. dimmed={active}
  12. dimmer={{ active, content }}
  13. onMouseEnter={this.handleShow}
  14. onMouseLeave={this.handleHide}
  15. src={`${APP_URL}/img/thumbnails/${this.props.thumbnail}.png`} />
Programming Language: ECMAScript

Keyframes

Source code viewer
  1. import styled, { keyframes } from 'styled-components';
  2.  
  3. const colorChangePulse = keyframes`
  4. 0% { color: #666; }
  5. 50% { color: lightgrey; }
  6. 100% { color: #666; }
  7. `;
  8.  
  9. const FileIsBeingDownloaded = styled.span`
  10. animation: 2s ${colorChangePulse} linear infinite;
  11. `;
  12.  
  13. render() {
  14. return (
  15. <FileIsBeingDownloaded>...</FileIsBeingDownloaded>
  16. );
  17. }
Programming Language: ECMAScript

Variables/Properties

Source code viewer
  1. const ListItem = styled.li`
  2. ${props => (props.isCurrentUser &&
  3. 'font-style: italic;')}
  4. ${props => (props.isSelectedClient &&
  5. 'background: #fce4ec;')}
  6. `;
  7.  
  8. return (
  9. <ListItem
  10. isCurrentUser={isCurrentUser}
  11. isSelectedClient={isSelectedClient}
  12. onClick={changeClient}
  13. onMouseMove={(e) => { setSelectedClient(idx, e); }} />
  14. );
  15.  
Programming Language: ECMAScript