Skip to content

Using styled-components with react-router #184

Closed

Description

@ForbesLindesay

react-router's <Link> component and react-modal2's <Modal> component accept additional classNames via separate properties. e.g. <Link> accepts activeClassName and <Modal> accepts backdropClassName and modalClassName. It would be great to have a way to style these using styled-components. Perhaps we could have something like:

const StyledLink = styled(Link)`
  color: palevioletred;
  display: block;
  margin: 0.5em 0;
  font-family: Helvetica, Arial, sans-serif;

  &:hover {
    text-decoration: underline;
  }
  &.active {
    color: red;
  }
`;

where &.active gets passed as a separate class name to the activeClassName property.

Activity

  1. geelen commented on Nov 12, 2016

    @geelen
    Member

    Hmm, that Link example should already work because :hover and :active are valid CSS pseudo selectors. But as for passing two classnames... I'm not sure that there's a nice way to do that.

    Perhaps we need a className helper that works a bit like keyframes?

    import { className } from 'styled-component'
    
    const backgroundClass = className`
      background-color: rgba(0,0,0,0.5);
    `
    
    const modalClass = className`
      background: white;
      border-radius: 0.5rem;
      padding: 2rem;
    `
    
    <Modal backdropClassName={backgroundClass} modalClassName={modalClass}/>

    This wouldn't work with function interpolations but might be a useful alternate. Plus, it would let you do things like Glamor:

    export default ({}) => (
      <div className={className`
          display: flex;
          padding: 1rem;
        `}>
          ...
      </div>
    )

    I've wanted to be able to do this occasionally when you have one or two styles to apply somewhere and you don't want to name a whole new component. There's probably a better name tho. @mxstbr what do you think?

  2. mxstbr commented on Nov 12, 2016

    @mxstbr
    Member

    The issue is that activeClassName for the Link refers to the route of the Link being active, not somebody clicking on it. This can't just be replicated with :active I'm pretty sure.

    I really really dislike the className thing. It breaks the whole premise of styled-components, I feel like there has to be a better escape hatch for the above case?

  3. ForbesLindesay commented on Nov 13, 2016

    @ForbesLindesay
    Author

    This is why I like the idea of :active being the true pseudo-class and .active targeting the activeClassName property. I would be fine with us using an alternative prefix other than . if people prefer.

    Another option might be something like:

    const StyledLink = styled(
      styled(Link)`
        color: palevioletred;
        display: block;
        margin: 0.5em 0;
        font-family: Helvetica, Arial, sans-serif;
    
        &:hover {
          text-decoration: underline;
        }
      `,
      'active'
    )`
      color: red;
    `;
  4. geelen commented on Nov 13, 2016

    @geelen
    Member

    Ah I see yeah I misread &.active as &:active in the original example. To be honest, I actually think turning &.active into activeClassName is really clever, but it's already a valid thing to do so I don't want to overload it.

    I suppose you could do &:pass-as-prop(activeClassName) { ... } or something else wacky like that. But tbh that's starting to put a lot of magic in there for an API that... is kinda clunky.

    IMO React Router could add a data-active attribute instead of applying a different classname, then we could do:

    const StyledLink = styled(Link)`
      color: palevioletred;
      display: block;
      margin: 0.5em 0;
      font-family: Helvetica, Arial, sans-serif;
    
      &[data-active] {
        color: red;
      }
    `;

    Lol, actually you can do this:

    const rando = btoa(Math.random())
    const StyledLink = styled(Link)`
      color: palevioletred;
      display: block;
      margin: 0.5em 0;
      font-family: Helvetica, Arial, sans-serif;
    
      &.${rando} {
        color: red;
      }
    `;
    <StyledLink activeClassName={rando}/>

    😂

  5. ForbesLindesay commented on Nov 14, 2016

    @ForbesLindesay
    Author

    The [data-active] is a neat solution for the react-router example (if the react-router team would accept the addition of the data-attribute). I don't think it solves the modal example where you would want to style multiple separate child components.

  6. geelen commented on Nov 14, 2016

    @geelen
    Member

    Sure it would!

    const backdropClassName = btoa(Math.random())
    const modalClassName = btoa(Math.random())
    
    const StyledModal = styled(Modal)`
      &.${backdropClassName} {
        background: rgba(0,0,0,0.5);
      }
      .${modalClassName} {
        background: ${ props => props.bg || 'white' };
        padding: 2rem;
      }
    `
    
    <StyledModal bg='papayawhip'
                 backdropClassName={backdropClassName} 
                 modalClassName={modalClassName} />
  7. mxstbr commented on Nov 15, 2016

    @mxstbr
    Member

    I think this could even be used for third-party component libraries:

    // lib/Modal.js
    
    // Use this class in the Modal component, notice the dot, that way users don't
    // have to be aware that it's even a class
    const backdrop = '.__my_lib__modal_backdrop__do__not__touch__'
    
    class Modal extends React.Component { /* ... */ }
    
    export {
      backdrop
    }
    export default Modal
    // app/Component.js
    
    import Modal, { backdrop } from 'my-lib'
    
    const StyledModal = styled(Modal)`
      &${backdrop} {
        background: rgba(0,0,0,0.5);
      }
    `

    Kind of like a fake child component selector 👌

  8. GertjanReynaert commented on Nov 15, 2016

    @GertjanReynaert

    @geelen If styled-components would go with the generated classNames approach from above, it might not be a bad solution to include a classname generator in styled-components that could take advantage of the better development classnames

    import { generateClassName } from 'styled-components';
    
    const modalClassName = generateClassName('modalClassName');
  9. ForbesLindesay commented on Nov 15, 2016

    @ForbesLindesay
    Author

    This is interesting. It relies on the className provided by styled-components being added to the top most html element rendered by the component being styled, but that's probably true in most cases and seems reasonable.

    It does seem like a lot of hoops to jump through, but I can see the desire to keep styled-components' API surface as small as possible.

  10. mxstbr commented on Nov 20, 2016

    @mxstbr
    Member

    As it turns out, this is an actual problem in ReactNative. Some RN primitives have props that expect styles to be passed in. (not just a value, so this is different from #149; thanks to @brunolemos for pointing that out!)

    ScrollView as an example has a contentContainerStyle prop which applies the styles one passes in "to the scroll view content container which wraps all of the child views.".

    The generateClassName solution doesn't work here, as there are no class names in ReactNative. 😕

    We might need to add support for passing arbitrary styles to a prop of the underlying primitive in core?

  11. jontro commented on Nov 30, 2016

    @jontro

    Just one more comment when discussing the Link item. If passing an invalid html prop (i,e one called inactive) you will get an error in the console due to this being passed all the way down to the Link itself

  12. jontro commented on Dec 2, 2016

    @jontro

    Another use case for multiple class names is <ReactCSSTransitionGroup> which takes multiple classes like this:

    <ReactCSSTransitionGroup
      transitionName={ {
        enter: 'enter',
        enterActive: 'enterActive',
        leave: 'leave',
        leaveActive: 'leaveActive',
        appear: 'appear',
        appearActive: 'appearActive'
      } }>
      {item}
    </ReactCSSTransitionGroup>
    
    <ReactCSSTransitionGroup
      transitionName={ {
        enter: 'enter',
        leave: 'leave',
        appear: 'appear'
      } }>
      {item2}
    </ReactCSSTransitionGroup>
    

    More info here https://facebook.github.io/react/docs/animation.html#custom-classes

  13. amccloud commented on Dec 7, 2016

    @amccloud

    This is how i'm currently providing an activeClassName to Link:

    const BaseNavItem = styled(Link)`
      color: red;
    `;
    
    const NavItem = styled(({className, ...props}) => <BaseNavItem {...props} activeClassName={className} />)`
      color: blue
    `;
    
    export default NavItem;

    I think this could be hidden behind some sort of helper:

    styled(someHelper(BaseNavItem, 'activeClassName'))
  14. geelen commented on Dec 21, 2016

    @geelen
    Member

    @amccloud that's clever, nice work!

  15. 7 remaining items

  16. rgdelato commented on Feb 7, 2017

    @rgdelato

    Funnily enough, I also ended up making a quick hack to support my own use case as well:
    https://github.com/rgdelato/styled-classnames

  17. rjhilgefort commented on Feb 10, 2017

    @rjhilgefort

    I think this could be hidden behind some sort of helper:

    styled(someHelper(BaseNavItem, 'activeClassName'))

    In case anyone wants it, here's an implementation of the helper described by @amccloud. Caveat, I'm using flow and ramda. You can obviously remove the flow annotations and translate omit to your implementation of choice.

    import React from 'react';
    import { curry, omit } from 'ramda';
    import { Link } from 'react-router';
    
    const omitProps = curry((
      omittedProps: Array<string>,
      Component: any,
      props: Object,
    ) => {
      const { children, ...rest } = omit(omittedProps, props);
      return <Component {...rest}>{children}</Component>;
    });
    
    const StyledLink = styled(omitProps(['foo', 'bar'], Link))`
      cursor: pointer;
    `;

    This is likely a similar implementation to @codepunkt's implementation, but as far as I can tell, it only supports one property.

  18. svrcekmichal commented on Feb 16, 2017

    @svrcekmichal

    Hey guys, is there some better solution for this when v2 is going to be released?

  19. rgdelato commented on Feb 16, 2017

    @rgdelato

    @svrcekmichal As far as I know, there's going to be a .attrs() property added to v2 (see #365) that solves this problem.

  20. mikehazell commented on Mar 6, 2017

    @mikehazell

    FWIW, this is working for me.

    import { Link } from 'react-router';
    import styled from 'styled-components';
    
    const NavItem = styled(Link)`
      background-color: blue;
    
      &.${(props) => props.activeClassName} {
        background-color: paleturquoise;
      }
    `;
    
    NavItem.defaultProps = {
      activeClassName: 'active',
    };
    
    export default NavItem;
  21. GGAlanSmithee commented on Mar 6, 2017

    @GGAlanSmithee
    Member

    And in v2, using attrs

    import { Link } from 'react-router';
    import styled from 'styled-components';
    
    const activeClassName = 'nav-item-active'
    
    const NavItem = styled(Link).attrs({
        activeClassName
    })`
      background-color: blue;
    
      &.${activeClassName} {
        background-color: paleturquoise;
      }
    `;
  22. svrcekmichal commented on Mar 6, 2017

    @svrcekmichal

    @mikehazell @GGAlanSmithee What do you think about this API? #522

  23. kitten commented on Apr 19, 2017

    @kitten
    Member

    As mentioned above, we currently don't need to follow up on this anymore, since we have the attrs method in v2.

  24. karolisgrinkevicius commented on Apr 29, 2017

    @karolisgrinkevicius

    In new react-router you may use NavLink instead of Link component. API for NavLink

  25. wojciech-bilicki commented on Jul 11, 2017

    @wojciech-bilicki

    Combining the @GGAlanSmithee and @karolisgrinkevicius solved the issue for me.

  26. jasan-s commented on Aug 14, 2017

    @jasan-s

    @karolisgrinkevicius it seems you still need to use attrs even with NavLink

  27. larsnolden commented on Oct 2, 2017

    @larsnolden

    I am running into issues using the new 'NavLink' from react-router-dom 4.2.2 following GGAlanSmithee's .attr approach:

    const activeClassName = 'nav-item-active'
    
    const NavItem = styled(NavLink).attrs({
       activeClassName
     })`
    
     color: blue;
    
     &.${activeClassName} {
       color: black;
     }
    `;
    
    //...
    
    <NavItem to='insights'>Insights</NavItem>

    Only the 'default' styles are being rendered. Using the 'activeStyle' prop on NavLink did not help either.

  28. mxstbr commented on Oct 2, 2017

    @mxstbr
    Member

    You need to pass the activeClassName to NavItem.

    <NavItem to='insights' activeClassName={activeClassName}>Insights</NavItem>

    I'm going to lock this issue now. Everything that needs to be said has been said and it's unnecessary to notify everybody for problems related to your own codebase.

    If you are having problems, please go to StackOverflow or open a new issue.

  29. locked and limited conversation to collaborators on Oct 2, 2017
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions