Home > database >  I want to customize the component with styled-components, but it doesn't work
I want to customize the component with styled-components, but it doesn't work

Time:07-07

Block.jsx code...

import React from 'react';
import styled from 'styled-components';
import { WHITE } from '../../constants/color';

const Wrap = styled.div`
  width: 100%;
  padding: 0 1rem;
  display: flex;
  align-items: center;
  box-sizing: border-box;
  background-color: ${WHITE};
`;

const Block = ({ children }) => {
  return <Wrap>{children}</Wrap>;
};

export default Block;

This is the Footer.jsx code to customize the Block component.

import React from 'react';
import Block from './Block';
import styled from 'styled-components';

const CustomBlock = styled(Block)`
  box-shadow: 0 -4px 3px rgba(0, 0, 0, 0.12), 0 4px 3px rgba(0, 0, 0, 0.24);
`;

const Footer = () => {
  return <CustomBlock>Footer</CustomBlock>;
};

export default Footer;

The value of box-shadow is not applied. Is there a workaround?

CodePudding user response:

The reason for this is that you are not passing the additional props that Styled Components is sending to your Block component, specifically the className prop. Therefore, Styled Components is not able to override any values on your Wrap component.

Try adjusting your Block component to be:

const Block = ({ children, ...props }) => {
  return <Wrap {...props}>{children}</Wrap>;
};

This will allow props that Styled Comonents passes to the Block component to be applied to the Wrap component, and therefore override accordingly.

CodePudding user response:

You need to add a className prop to the Block component in order for styled-components to inject the styles. You can do that by doing the following:

const Block = ({ children, className }) => {
  return <Wrap className={className}>{children}</Wrap>;
};

See styling any components in the docs

  • Related