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:
<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>;
);
};