Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combine multiple styled elements with styled-components

I know that we can extend or add styling to existing components with styled-components like the Link component of react-router-dom. The said feature is indicated here. But, my problem is, how can I combine two or more existing components then add some more styles?

In my case, I have a reusable component for text elements like span, p and a with standard font-size, font-weight, etc. At the same time, I want to use the react-router-dom's Link component. Currently, I have something like this:

import styled from 'styled-components';
import { Link } from 'react-router-dom';
import { TextElement } from '../common';

/*
Can I do something like this?
const MyLink = styled(Link, TextElement)`
    margin: 10px 0;
`;

or this?
const MyLink = styled([Link, TextElement])`
    margin: 10px 0;
`;
*/

const MyPage = props => (
   <>
       <MyLink to="/next-page" />
   </>
);

Any suggestion would be appreciated.

EDIT

My TextElement component is just something like this:

const Element = styled.span`
   font-size: 13px;
   font-weight: 500;
`;

// These styles are sample only. Actual styles depend on a "variant" prop.
// I did not show it here since it doesn't have to do with the question I'm asking.

export default ({ tag }) => (<Element as={tag} />);
like image 327
sdabrutas Avatar asked May 23 '19 00:05

sdabrutas


People also ask

Can I use mixin in styled-components?

While Styled Components doesn't have anything out of the box for mixins, per se, we can use it to achieve exactly what we need.

Can you add Classnames to styled-components?

Finally, you can use styled-components with any CSS framework. For example, let's create a Button component with Bootstrap styling. We used the attrs method to add a className attribute to the component with btn btn-primary value.

Can you style a styled-component?

Styled Components allow you to style any custom component that you've created. First, the custom component must receive the prop className and pass it to the underlying DOM element. Once that is done, pass the custom component to the styled function and invoke it as a Tagged Template to receive a new Styled Component.


1 Answers

You can use mixin for this using css helper. Let's say you put the code for TextElement in a spaced mixin like:

import { css } from 'styled-components';

const spaced = css`
  margin: 10px 0;
`;

And another mixin for Link

const styledLink = css`
  color: blue;
`;

Then you can define your MyLink as:

import styled from 'styled-components'

const MyLink = styled(Link)`
  ${spaced}
  ${styledLink}
`;
like image 97
Vishnu Avatar answered Sep 30 '22 08:09

Vishnu