Search code examples
reactjsstyled-components

React: Can we extend styled-components with props?


Can we extend an existing styled-componet while simultaneously passing props? This helps in centralizing all style related objects. An (invented) example below:


const Foo = styled.div`
  height: ${({ height }) => `${height && '12'}px`};
`;

// Currently possible: 
const Bar= styled(Foo).attrs({ tabIndex: 0 })`
  color: red;
`;

// Invented!! Does not work
const Baz = styled(Foo).props({ height: '14' })`
  color: red;
`;

Is there a way to achieve this "props", just like we can use "attrs" in styled-components?


Solution

  • Something like this could work:

    const Baz = styled((props) => <Foo height="14"  {...props} />)