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

How to receive inline styles and classes in a component

I’m creating a custom Container component and I would like to be able to receive inline styling and classes applied to this component. The component syntax:

const Container = ({ children }) => {
  return <div  className={classes.container}>{children}</div>;
};

When using it I would like for example to add inline styles:

<Container style={{ backgroundColor: "red" }}>
  <p>hello</p>
</Container>

Or classes:

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

<Container className={classes.aClass}>
  <p>hello</p>
</Container>

But what is the correct syntax in Container component to receive those? I’m sorry I know that this is a basic question, it was probably asked before but I cannot find it and probably I don’t search with the right terms

>Solution :

You can receive the style as props and pass it to the container’s div element

const Container = ({ children, style }) => {
  return (
    <div 
      className={classes.container}
      style={style}
    >
      {children}
    </div>;
  );
};

For CSS classes, you will have to merge your existing classes with the classes passed by users. For that, I would recommend a tiny library like clsx which helps us combine with ease

import clsx from "clsx"

const Container = ({ children, style, className }) => {
  return (
    <div 
      className={clsx(classes.container, className)}
      style={style}
    >
      {children}
    </div>;
  );
};
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