I'm trying to add a class name to a child component, preserving the original classes that may be set to the component.
Here is the code:
import React, { Component } from "react";
import PropTypes from "prop-types";
class ClassExtender extends Component {
getChildrenWithProps = () => {
let addedClass = "my-new-css-class-name";
return React.Children.map(this.props.children, child =>
React.cloneElement(child, { className: [child.className, addedClass] })
);
};
render = () => {
return this.getChildrenWithProps();
};
}
export default ClassExtender;
I'm getting a wrong result when my component renders:
<div class=",my-new-css-class-name">Test</div>
That points to two possible problems:
React.cloneElement(child, { className: child.className + " " + addedClass });
. That is a easy step.child.className
is returning null
. How can I retrieve the current classe(s) attached to the child component ?child.className is returning null. How can I retrieve the current classe(s) attached to the child component ?
child.props.className
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With