Search code examples
reactjsstyled-components

How to inherit style from another component?


I want to take styling from the component 'Tab' which is a react-router-dom Navlink and apply it to my new component 'DropdownTab' which is a 'div'. How can I inherit the styling without making it a NavLink? I want to do this to avoid duplicate lines of code.

const Tab = styled(NavLink)`
  padding: 0 20px;
  height: ${variables.height};
  line-height: ${variables.height};
`;

// Should be the component 'Menu' and is now the component NavLink
const DropdownTab = styled(Tab)`
`;

Solution

  • Perhaps you can use as?

    const DropdownTab = styled(props => <Tab as="div" {...props} />)`
      /* additional styles */
    `;
    

    That's ugly though, so maybe you can just extract the common styles into a variable:

    const commonStyles = `
      /* common styles */
    `
    
    const Tab = styled(NavLink)`${commonStyles}`
    const DropdownTab = styled('div')`${commonStyles}`
    

    If you have prop-based style in your component (i.e color: ${props => props.color}, you'd need to use css helper:

    import styled, { css } from 'styled-components'
    
    const commonStyles = css`
      color: ${({ isActive }) => isActive ? 'red' : 'blue' };
    `
    
    ...