Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ReactJS: How to add a className to a child component

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:

  1. The comma may indicate I need to change code to React.cloneElement(child, { className: child.className + " " + addedClass });. That is a easy step.
  2. child.className is returning null. How can I retrieve the current classe(s) attached to the child component ?
like image 962
Mendes Avatar asked Jan 28 '23 10:01

Mendes


1 Answers

child.className is returning null. How can I retrieve the current classe(s) attached to the child component ?

child.props.className
like image 198
Nicholas Tower Avatar answered Jan 31 '23 21:01

Nicholas Tower