James
James

Reputation: 3815

Splitting Styled-Components into multiple files but export them as one file

When I was building my application, I didn't realize that I am going to end up with more than a hundred styled components. Consequently, I was putting them in the same file like this:

export const StyledTabs = styled(Tabs)`
  display: inline-flex !important;
  margin-left: 15% !important;
`;

export const StyledTab = styled(Tab)`
  display: inline-flex !important;
  margin-left: 0% !important;
  padding: 0 !important;
`;

... And the application imports them like this:

import { StyledTabs, StyledTitle } from "StyledComponents";

I want to split the StyledComponents.js file into multiple files by, for example, UI logic (header, footer, containers, etc..) but somehow, import them back into StyledComponents.js so I don't have to refactor the entire application.

Is something like this possible:

HeaderSC.js

export const StyledTabs = styled(Tabs)`
  display: inline-flex !important;
  margin-left: 15% !important;
`;

export const StyledTab = styled(Tab)`
  display: inline-flex !important;
  margin-left: 0% !important;
  padding: 0 !important;
`;

StyledComponents.js

import { StyledTabs, StyledTitle } from "../styling/HeaderSC";

..and then the app still referring to StyledTabs or any other styled component from StyledComponents.js file?

Upvotes: 3

Views: 8230

Answers (2)

amaltapalov
amaltapalov

Reputation: 21

You can do it like following this steps.

1) You create folder Tabs

2) Inside Tabs folder you create index.js and styled.js files.

In index.js file:

import {StyledTabs, StyledTitle } from "./styled

In styled.js file:

export const StyledTabs = styled(Tabs)`
  display: inline-flex !important;
  margin-left: 15% !important;
`;

export const StyledTab = styled(Tab)`
  display: inline-flex !important;
  margin-left: 0% !important;
  padding: 0 !important;
`;

Upvotes: 2

Anshul Sahni
Anshul Sahni

Reputation: 666

You can create a folder StyledComponents and inside that create a default import file index.js, from which all your exports will be facilitated.

In the very same folder create different files for different components like StyledTabs.js and StyledTitle.js then index.js of the very same folder you can do

export StyledTab from './StyledTab';
export StyleTitle from './StyledTitle';

This way your import { StyledTab } from 'path/to/StyledComponents' will work flawlessly

Upvotes: 8

Related Questions