Reputation:
I have a React component styled using styled-components, but can it be apply style again? My button is a react component
import Button from "./Button";
Then somewhere else I add margin-top, it don't apply the style.
//margin-top has no effect?
const ButtonStyled = styled(Button)`
margin-top: 100px;
`;
export default function App() {
return <ButtonStyled>My button</ButtonStyled>;
}
Demo here https://codesandbox.io/s/goofy-montalcini-l47kp?file=/src/App.js:144-150
Upvotes: 1
Views: 1998
Reputation: 2979
In order for the styled
function to work, the component must accept a className
prop. Now, when you define Button
:
const Button = ({ children }, props) => {
return <ButtonStyled {...props}>{children}</ButtonStyled>;
};
You try to spread the props to ButtonStyled
, which is good, you just mis typed the place of props
. Try this:
const Button = ({ children, ...props }) => {
return <ButtonStyled {...props}>{children}</ButtonStyled>;
};
This way, the className
prop (which is applied by styled()
) will be passed onto StyledButton
.
Upvotes: 3
Reputation: 334
I have seen two options to override the css.
import styled, { css } from "styled-components";
const ButtonStyled = styled.button`
${(props) => {
return css`
margin-top: 10px;
width: 200px;
padding: 16px 0;
border: 1px solid;
color: black;
font-size: 16px;
font-weight: 900;
border-radius: 5px;
${props.newStyled}
`;
}}
`;
const Button = ({ children, ...props }) => {
return <ButtonStyled {...props}>{children}</ButtonStyled>;
};
// OPTION 1: WRAPPER THE COMPONENT
function Question7_option1() {
const DivStyled = styled.div`
button {
margin-top: 100px;
}
`;
return (<DivStyled>
<Button>Button</Button>
</DivStyled>);
}
// OPTION 2: NEW STYLES THROUGH PROPS
function Question7_option2() {
const newStyled = css`
margin-top: 100px;
`;
return (<Button newStyled={newStyled}>Button</Button>);
}
export default Question7_option2;
I hope I've helped you
Upvotes: 0