Reputation: 10630
right now i have a higher-order-component that allows me juice up any component, it:
color
propit looks like this:
// withColor.js
import React from 'react'
import styles from './withColor.css'
import cn from 'classnames'
const withColor = TargetComponent => {
const WrappedComponent = props => {
// color is something like "black" or "red" and has a matching css class
const { className, color, ...rest } = props
const enhancedClassName = cn(className, {
[styles[`Color-${color}`]]: color,
})
return <TargetComponent className={enhancedClassName} {...rest} />
}
return WrappedComponent
}
example usage:
// box.js
import React from 'react'
import withColor from '../hocs/withColor'
const Box = props => <div data-box {...props} />
export default withColor(Box)
can i use react hooks to do this instead? what would it look like?
Upvotes: 0
Views: 812
Reputation: 281764
All you need is to write a custom hook that performs the above logic. Infact its not even a hook but a common function
const useWithColor = (props) => {
const { className, color, ...rest } = props
const enhancedClassName = cn(className, {
[styles[`Color-${color}`]]: color,
})
return {...rest, enhancedClassName};
}
and use it like
export default props => {
const dataProps = useWithColor(props);
return <div data-box {...dataProps} />
}
Upvotes: 2