4

Given the following React component:

class MyComponent extends Component {
  sayGreeting = () => {
    return this.props.greeting;
  }

  render() {
    return (
      <div>{this.sayGreeting()}</div>
    );
  }
}

greeting is passed via props and is just a string message. Given sayGreeting() might be used in multiple components, with the exact same definition, would it be possible to extract it into a file (see the following code) and then somehow include it in each component as needed. This is like the include module (or mixin?) pattern in programming languages like Ruby.

export const sayGreeting = () => {
  return this.props.greeting;
};

I was able to do it by importing sayGreeting from that file and setting the prototype of MyComponent as such:

import { sayGreeting } from './someFile';
// ...
MyComponent.prototype.sayGreeting = sayGreeting; 

But the issue is the "this" keyword, so props will not be defined. I tried binding in the constructor using this.sayGreeting = this.sayGreeting.bind(this), but it didn't work.

nbkhope
  • 7,360
  • 4
  • 40
  • 58

2 Answers2

2

You can use a higher-order component:

const myHOC = (composedComponent) => { 
  return class extends React.Component {
    sayGreeting = () => {
      return this.props.greeting;
    }

    render() {
      return <ComposedComponent sayGreeting={ this.sayGreeting } />;
    }
  };
};

class MyComponent extends React.Component {
   render() {
      return <div>{this.props.sayGreeting()}</div>
   }
}

export default MyHOC(MyComponent);
Carlos Martinez
  • 4,350
  • 5
  • 32
  • 62
1

Pass this into the function.

export const sayGreeting = ({props}) => {
  return props.greeting;
};

Then to use after importing: sayGreeting(this)

Chip Dean
  • 4,222
  • 3
  • 24
  • 36