-
-
Save Dman757/872a65944577cdbfc6476dd5af494b96 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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 extraexample: