Jonathan Calb Jonathan Calb - 3 months ago 7
Javascript Question

Decorate imported React component with higher order component

I know how to decorate a component before exporting it like this:

export default ButtonDecorator(MainButton)


But if I try to make a index to import it and decorate it differently for some cases. It wont work.

Here is the example of the index:

import MainButton from './main/main_button'
import BackButton from './back/back_button'

import { ButtonDecorator, LinkDecorator } from 'decorators'

export {
ButtonDecorator(MainButton) as MainButton,
LinkDecorator(MainButton) as MainHrefButton,
BackButton
}


And the higher order component:

import React, { Component } from 'react'

let Btn = InnerComponent => {
class NewBtn extends Component {

constructor(props) {
super(props)
}

render() {
return (
<button onClick={this.props.onClick}>
<InnerComponent disabled={this.props.disabled} />
</button>
)
}
}

return NewBtn
}

export default Btn


What is the right way to do this?

Answer

As far as I know export requires a name (variable), and not a function invocation. Try this:

const ButtonDecoratedMainButton = ButtonDecorator(MainButton);
const LinkDecoratedMainButton = LinkDecorator(MainButton);

export {
    DecoratedMainButton as MainButton,
    LinkDecoratedMainButton as MainHrefButton,
    BackButton
}
Comments