1
votes

I like using the styled components naming convention where you do <S.SomeName>...</S.SomeName>, however I've encountered a problem where I need to import a component's styles and then some shared styled components as well but I can't import it as S again.

Here is my folder structure:

src
    ├── api
    │   ├── verb-api.js
    │   └── list-api.js
    ├── axios
    │   └── index.js
    ├── components
    │   └── ListsCard
    │       ├── SubListsCard
    │       │   ├── AnalyticsPage.js
    │       │   ├── VerbsPage.js
    │       │   ├── index.js
    │       │   └── styles.js
    │       ├── index.js
    │       └── styles.js
    ├── hooks
    │   ├── mutations
    │   │   ├── useListMutation
    │   │   └── useVerbMutation
    │   ├── useClickOutside
    │   └── useFocusInput
    ├── routes
    │   ├── Home.js
    │   ├── index.css
    │   └── index.js
    └── index.js

I need to use the styles from SubListsCard/styles.js and ListsCard/styles.js for my SubListsCard component. (I might make a folder called shared an import from that, instead of importing from ListsCard/styles.js).

My Solution was just import the shared styled components into the SubListsCard/styles.js and export it out:

import styled from "styled-components"
import {SomeComponent, OtherComponent} from "../styles"

export {SomeComponent, OtherComponent}; 

const Name = styled.div`

    ...

`;

is there any better way of doing this?

Thanks in advance :)

1
I'm not sure I understand the problem. Is there any error you're getting? Why don't you just import what you need and alias it with import { SomeComponent as foo } or similar? - F.P
My solution works, but I was wondering if anyone does it another way, I think the S naming convention is quite common when using styled components so I was wondering what people do if they need to import styles from two different places. Maybe it’s a stupid question. - jake_prentice
What I'm saying is that I don't even understand what problem your solution solves - F.P

1 Answers

2
votes

I like the approach mentioned at https://zzzzbov.com/blag/styled-components-naming-convention from all the solutions that i have came across so far.

Header.js

import { Component } from "react";
import { Navbar } from "react-bootstrap";
import { $Header } from "./style";

class Header extends Component {
    render() {
        return (
            <$Header>
                <Navbar>
                </Navbar>
            </$Header>
        )
    }
}

export default Header;

style.js

import styled from 'styled-components'; 

export const $Header = styled.header`
    z-index: 1;
`