U
U
unsafePtr2017-03-28 15:06:19
React
unsafePtr, 2017-03-28 15:06:19

What to do with common methods of React components?

I know that it is not recommended to inherit components in React, but what about common methods that will be used in several components. For example, we have a method:

getDefaultState() {
        return {
            sellCurrency: 'EUR',
            buyCurrency: 'GBP',
        }
    }

And instead of declaring it in each component, you can create a base component (which, however, will not have a render function) and inherit from it.
export default class BaseComponent extends Component {
    getDefaultState() {
        return {
            sellCurrency: 'EUR',
            buyCurrency: 'GBP',
        }
    }
}

class Component1 extends BaseCoponent {
    constructor(props) {
        super(props);

        this.state = this.getDefaultState();
     }
}

class Component2 extends BaseComponent {
    constructor(props) {
        super(props);

        this.state = this.getDefaultState();
   }
}

And I checked, and each component will create its own state. Who resorts to what methods, and is there an idea how best to implement this?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
Mikhail Osher, 2017-03-28
@unsafePtr

TL;DR: Higher Order Components
https://facebook.github.io/react/docs/higher-order...
https://medium.com/@franleplant/react-higher-order...
https:// gist.github.com/sebmarkbage/ef0bf1f338a718...
https://egghead.io/lessons/react-react-fundamental...
https://www.sitepoint.com/react-higher-order-compo...

I
Islam Ibakaev, 2017-03-28
@devellopah

output the shared state to the parent component

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question