No internet connection
  1. Home
  2. Programming

How to make a parametric function to return the Custom React Component depending on the given param?

By Zohrab @Zohrab2018-05-05 13:47:11.105Z2018-05-05 14:12:13.507Z

I want to make a parametric function to return the React Component with depending the parameter I will give when will call it...
for example
function customRender(----){
return(< ---- />)
}

for if I call ----> customRender(App);
it might return the <App/> component

  • 1 replies
  1. S
    Suren Atoyan @SurenAt2018-05-05 14:30:55.303Z

    You can use decorators design pattern and factory. For getting more flexibility you can use "Factory of decorator".

    It can look like this.

    validator.js

    export default rules => OriginalComponent => class ValidatableComponent extends PureComponent {
    
      // it's just an example
      isValid() {
        const { value } = this.state;
        return (value > rules.min && value < rules.max);
      }
    
      render() {
        return (
          {!this.isValid() && <span>rules.errorMessage</span>}
          <OriginalComponent {...this.props} />
        )
      }
    }
    

    And usage of it.

    import Validator from './validator';
    
    @Validator({
      min: 12,
      max: 32,
      errorMessage: '...',
      ...
    })
    class MyComponent extends PureComponent {
      
    }