Sunday, June 2, 2024
 Popular · Latest · Hot · Upcoming
69
rated 0 times [  71] [ 2]  / answers: 1 / hits: 5124  / 4 Years ago, fri, august 21, 2020, 12:00:00

I have a problem on which I cannot find a simple solution. So this is my Header:


const Header = ({ title }) => {
return (
<div className={styles.Header}>
<h1>{title}</h1>
<button>
{EXIT}
</button>
</div>
);
};

How can I apply custom styles with styled-components for h1 and button elements? I tried


const CustomHeader = styled(Header)`
${h1} ${button}
`;

const h1 = styled(h1)`
max-width: 500px
`
const button = styled(button)`
padding-left: 100px
`

but this is not working, I get an error in terminal.
I also tried this:


  return (
<CustomHeader>
<div className={styles.Header}>
<h1>{title}</h1>
<button>
{EXIT}
</button>
</div>
</CustomHeader>
);
};

const CustomHeader = styled(Header)`
h1 {
max-width: 500px;
}
button {
padding-left: 100px;
}
`;

Any help will be appreciated.


More From » css

 Answers
2

You're almost there.


Its not working because you are setting className directly on div element of your Header component.


According to the styled-component documentation:


The styled method works perfectly on all of your own or any third-party components, as long as they attach the passed className prop to a DOM element.


https://styled-components.com/docs/basics#styling-any-component


So, in your case you need to:




const Header = ({ title, className }) => {
return (
<div className={className}>
<h1>{title}</h1>
<button>EXIT</button>
</div>
);
};

const CustomHeader = window.styled(Header)`
h1 {
max-width: 500px;
}
button {
padding-left: 100px;
}
`;

const App = () => {
return (
<React.Fragment>
<Header className='' title={title} />
<CustomHeader title={title} />
</React.Fragment>
);
};

ReactDOM.render(
<React.StrictMode>
<App />
</React.StrictMode>,
document.getElementById('root')
);

<script src=https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js></script>
<script src=https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js></script>
<script src=//unpkg.com/[email protected]/dist/styled-components.min.js></script>
<div id=root></div>




So, i set Header like this:


const Header = ({ title, className }) => {
return (
<div className={className}>

And where i did <Header className='' title={"title"} /> you can do like this:


<Header className={styles.Header} title={"title"} />


[#2839] Tuesday, August 18, 2020, 4 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
estefanib

Total Points: 508
Total Questions: 104
Total Answers: 83

Location: Lebanon
Member since Sun, Aug 2, 2020
4 Years ago
;