Skip to content

Instantly share code, notes, and snippets.

@Dman757
Last active December 4, 2019 23:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Dman757/872a65944577cdbfc6476dd5af494b96 to your computer and use it in GitHub Desktop.
Save Dman757/872a65944577cdbfc6476dd5af494b96 to your computer and use it in GitHub Desktop.
import React from 'react';
// API Refrences
// React.cloneElement https://reactjs.org/docs/react-api.html#cloneelement
// React.Children.map https://reactjs.org/docs/react-api.html#reactchildrenmap
const AppendClass = ({ children, newClass = '' }) => {
return React.Children.map(children, child => {
const modifiedProps = {
...child.props,
className: child.props.className // check to preserve the classNames already applied
? `${child.props.className} ${newClass}`
: newClass,
};
return React.cloneElement(child, modifiedProps);
});
};
export default AppendClass;
@Dman757
Copy link
Author

Dman757 commented Dec 4, 2019

Usage is to add a class to a child component inline without modifying the existing component code.

It takes the child component it's wrapped around and spits out a clone with the appended className prop added. No extra

added to the DOM just the cloned component.

example:

<AppendClass newClass="whatever">
  <MyComponent/>
</AppendClass>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment