Reputation: 928
I'm just getting into styled-components
and am having a little bit of an issue. I'm trying to extend a button
through different files and for some reason it imports as undefined
This error initially appeared with a NavLink
component which led to believe it might be a react issue but it also happens with a styled.a``;
so I don't think that's it.
StyledComponents.jsx
import styled from 'styled-components';
export const Button = styled.a`
// general styling
`;
App.jsx
import { Button } from './StyledComponents/StyledComponents';
console.log(Button); // this works fine
export const MainButton = styled(Button)`
// a little color and other styles
`;
Banner.jsx
import { MainButton } from '../App';
console.log(MainButton); // returns undefined
// if I omit the console logging above, this gives error of undefined
const _MainButton = styled(MainButton)`
// specific styles for this component
`;
I am not really sure what is going on. I am also not sure if this is the correct way to layer these styled components. If someone could share some insight, it would be much appreciated!
Upvotes: 3
Views: 8105
Reputation: 1400
So okay, this export convolution is the problem. You're importing a button from StyledComponents.jsx
into App.jsx
, which you then export as MainButton
, and then import again into Banner.jsx
, which is rendered in the LandingPage
, which is rendered in the App.jsx
. Whew. I literally solved this by just moving the MainButton
definition and export into another file. I'm not sure why, but that's what it was. Keeping styled components in a dedicated files is a good idea! For example, moving the MainButton
to a different file:
/StyledComponents/StyledComponents.jsx
export const MainButton = styled(Button)`
//styles go here
`;
And then changing the import:
Banner.jsx
import { MainButton } from '../StyledComponents/StyledComponents';
works just fine!
In general, though, if you want to layer stuff with styled-components, I like to keep it in a single file. You don't have to export them all if you don't need all, but you also can:
const TitleBase = styled.h1`
text-transform:uppercase;
font-size: 1rem;
`;
export const GreenTitle = styled(Title)`
color: green;
`;
export const RedTitle = styled(Title)`
color:red;
`;
Just make sure they are in order. You can't define Title
after RedTitle
eg.
A small tip: it's also okay to use .js
extension instead of .jsx
, but you're free to do whatever you want!
Upvotes: 3