Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Use Props for child element style

In React project I have a parent and a child component. I want to pass the props down and use those for styling in the child component.

Parent

<StyledToolbar>
   <Logo sx={{display: "block", width: 130}}  />
   ...
</StyledToolbar>

Logo.jsx

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel


const Logo = (props) => {
    return (
        <img src="/assets/logo.svg"
             alt="My Logo"
             style={props.sx}
        />
    )
}
export default Logo

The logo is displayed but it is not styled correctly. Rendered HTML looks like this:
<img src="/assets/logo.svg" alt="My Logo" style="width: 30px; height: 30px;">

>Solution :

In React you pass the style object via the style prop. So your logic with the sx doesn’t work.

Here is the correct code:

Parent Component

<StyledToolbar>
   <Logo style={{display: "block", width: 130}}  />
   ...
</StyledToolbar>

Child Component

const Logo = (props) => {
    return (
        <img src="/assets/logo.svg"
             alt="My Logo"
             style={props.style}
        />
    )
}
export default Logo
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading