React - adding class to children components

For the sake of simplicity:

const StyleInjector = ({ children }) => {
   const StyledChildren = () =>
    React.Children.map(children, child =>
      React.cloneElement(child, {
        className: `${child.props.className} ${PUT_YOUR_CLASS_HERE}`
      })
    );

  return <StyledChildren />;
};

I figured it out a week ago, this is what I wanted :

export default class ContainerComponent extends React.Component {
    constructor(props) {
        super(props);

        this.modifyChildren = this.modifyChildren.bind(this);
    }

    modifyChildren(child) {
        const className = classNames(
            child.props.className,
            {...otherClassses}
        );

        const props = {
            className
        };

        return React.cloneElement(child, props);
    }
    render() {
        return (<div>
            {React.Children.map(this.props.children, child => this.modifyChildren(child))}
        </div>);
    }
}

Weeks back I had a scenario of carousal to be implemented in react, nothing fancy just simple toggling of active class. I followed this approch, works like a charm but let me know this is a good approach.

{
 this.props.children.map((slide, index) => {
   return React.cloneElement(slide, {
      key: index,
      className: (this.state.currentActiveIndex === index) ?'active' : ''
   });
 })
}

Tags:

Reactjs