Reputation: 1145
I'm trying to make an HOC that assign values to the parameter "color" in an icon component in React js. I have 3 different colors. They come as follow : pimary is #f7a014 secondary is #dd8b08 ternary is #56t00
So I can do :
<MyComponent color='primary' />
Here is my withColor HOC :
import React from 'react';
import propTypes from 'prop-types';
function mapColors(color) {
if (color === 'primary') {
return '#f8af39';
}
if (color === 'secondary') {
return '#fff';
}
if (color === 'ternary') {
return '#004c64';
}}
export const withColor = WrappedComponent => {
const NewComponent = ({ color, ...props }) => (
<WrappedComponent color={mapColors(color)} {...props} />
);
NewComponent.propTypes = {
color: propTypes.oneOf(['primary', 'secondary', 'ternary']),
};
return NewComponent;
};
export default withColor;
Here is my component with the icon in it :
import React from 'react';
import { RequestCloseModal } from 'HOC/connectModals';
import { compose } from 'redux';
import {
Collapse,
Modal,
ModalHeader,
ModalBody,
ModalFooter,
} from 'reactstrap';
import { ChevronDown, ChevronUp } from 'react-feather';
import PropTypes from 'prop-types';
import Industrie from 'components/Icons/Industrie';
import FinancerContainer from 'backoffice/containers/Financer/FinancerContainer';
import withContainer from 'HOC/withContainer';
import withColor from 'HOC/WithColor';
class FinancerMatchingDetails extends RequestCloseModal {
static propTypes = {
isOpen: PropTypes.bool,
};
constructor(props) {
super(props);
this.state = {
collapse: false,
};
}
toggle = () => {
this.setState({ collapse: !this.state.collapse });
};
render() {
const { isOpen } = this.props;
return (
<Modal size="xxl" isOpen={isOpen} toggle={this.close}>
<ModalHeader toggle={this.close}>
<div className="col-md-3">
<h4>Some text</h4>
<p>Some text</p>
</div>
</div>
</div>
<div>
<h4>Some text</h4>
{this.state.collapse ? (
<ChevronUp height={20} onClick={this.toggle} />
) : (
<ChevronDown height={20} onClick={this.toggle} />
)}
</div>
</ModalBody>
<ModalFooter>
<div className="container">
<Collapse isOpen={this.state.collapse}>
<div className="row">
<div className="col">
<MyIcon color="primary" />
</div>
</Collapse>
</div>
</ModalFooter>
</Modal>
);
}
}
export default compose(withContainer(FinancerContainer), withColor)(
FinancerMatchingDetails,
);
I'm new to HOC and can't make it to assign the color primary. Thanks for your help.
Upvotes: 0
Views: 257
Reputation: 1101
You defined HOC but never pass any components through it. E.g.
import withColor from 'HOC/WithColor'; // your HOC
import SomeComponent from 'SomeComponent'; // component that you would like to use with HOC
then you need to define a component that is the result of HOC applied to your component:
const ColoredComponent = withColor(SomeComponent);
and then you can use it as you expected:
<ColoredComponent color="primary" />
Upvotes: 1