Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React inline style doesn't affect my custom component

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!

like image 665
DSCH Avatar asked Mar 10 '19 16:03

DSCH


People also ask

Why are inline styles Bad React?

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.

Which of the following Cannot be used with React inline styles?

Inline styles cannot be used to target pseudo-classes or pseudo-elements.


1 Answers

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>
like image 60
Tholle Avatar answered Oct 10 '22 05:10

Tholle