I have a custom component where I need to add it margin-top in in of my uses. I tried <MyComponent style={{ marginTop: '10px' }}>
and also
const myStyle = { marginTop: '10px' };
`<MyComponent style={myStyle}>`;
And it both don't work.
When I do the same in the same file for a simple <div>
(e.g. <div style={{ marginTop: '10px' }}>
and <div style={myStyle}>
it works as expected.
Maybe it is important to mention that the wrapping element of my custom component (<MyComponent/>
) is a styled-component
.
Would appreciate anyway to fix it or make it work. Thanks!
One of the main reasons that inline styling is not a good choice for your application is because it does not support (or it has really poor support) for CSS features. Every application nowadays might have to end up using some selectors such as :hover , :active , :focused , etc.
Inline styles cannot be used to target pseudo-classes or pseudo-elements.
The style
prop will be just be like any other prop for a custom component. You need to take the style
prop given to MyComponent
and add it to the style
prop of one of the elements inside MyComponent
.
Example
function MyComponent(props) {
return <div style={props.style}>MyComponent</div>;
}
function MyBrokenComponent() {
return <div>MyBrokenComponent</div>;
}
function App() {
const style = { marginTop: "10px", backgroundColor: "green" };
return (
<div>
<MyBrokenComponent style={style} />
<MyComponent style={style} />
</div>
);
}
ReactDOM.render(<App />, 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>
<div id="root"></div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With