I have multiple ponents in my project, most of which are simple containers for specific content, with a bit of styling. They typically look like this—
function Portion(props) {
return (
<div id={props.id} className={`portion ${props.className}`}>
{props.children}
</div>
)
}
I have the extra ${props.className}
so that it’s easy to add more classes if need be. Now, the problem is that if there are no extra classes for that element, React adds an undefined
class.
How can I avoid that?
I have multiple ponents in my project, most of which are simple containers for specific content, with a bit of styling. They typically look like this—
function Portion(props) {
return (
<div id={props.id} className={`portion ${props.className}`}>
{props.children}
</div>
)
}
I have the extra ${props.className}
so that it’s easy to add more classes if need be. Now, the problem is that if there are no extra classes for that element, React adds an undefined
class.
How can I avoid that?
Share Improve this question asked Apr 22, 2019 at 11:14 Sujan SundareswaranSujan Sundareswaran 2,5512 gold badges14 silver badges26 bronze badges 2-
initialize
props.className=""
– Oram Commented Apr 22, 2019 at 11:17 - set default prop values – Junius L Commented Apr 22, 2019 at 11:18
3 Answers
Reset to default 6Try using
${props.className || ""}
you can add a condition;
className={`portion ${props.className || ””}`}
You can add a default value to the className if you destructure your props
function Portion({className = '', id, children}) {
return (
<div id={id} className={`portion ${className}`}>
{children}
</div>
)
}