Home > OS >  styled components inheritance not working
styled components inheritance not working

Time:10-28

The problem is that I have one DefaultButton and I code custom styled components for it. I have a different button called PrimaryButton and I want to write style properties to it. But he doesn't see it.

This is folder structure

enter image description here

DefaultButton.tsx

import * as S from "./styles";

const DefaultButton = ({ children }: any) => {
  return <S.Button>{children}</S.Button>;
};
export default DefaultButton;

PrimaryButton.tsx

import styled from "styled-components";

import { colors } from "theme";
import DefaultButton from "./DefaultButton";

const PrimaryButton = styled(DefaultButton)`
  background-color: ${colors.mainColors.blueOcean};
`;
export default PrimaryButton;

index.tsx Page

import { PrimaryButton } from "components";

import type { NextPage } from "next";
import Head from "next/head";

const Home: NextPage = () => {
  return (
    <div>
      <Head>
        <title>Create Next App</title>
        <meta name="description" content="Generated by create next app" />
        <link rel="icon" href="/favicon.ico" />
      </Head>
      <h1>hessssllo</h1>
      <PrimaryButton>Sıgn in</PrimaryButton>
    </div>
  );
};

export default Home;

styles.tsx

import styled from "styled-components";

export const Button = styled.button`
  font-family: "DM Sans", sans-serif;
  cursor: pointer;
  display: flex;
  justify-content: center;
  align-items: center;
`;

Components index.ts for importing

export { default as Button } from "./Buttons/DefaultButton";
export { default as PrimaryButton } from "./Buttons/PrimaryButton";

CodePudding user response:

You are trying to set DefaultButton into PrimaryButton, it looks like <button><button>text</button></button>, hence you cannot see the styled button. So, all you have to do, just get the styled button from the styled.ts.

PrimaryButton.tsx

import styled from "styled-components";

import { Button } from "./styles";

const PrimaryButton = styled(Button)`
  background-color: blue;
  color: white;
`;
export default PrimaryButton;

Edit dazziling-code

  • Related