Home > Net >  Passing a class into a React component so that it can create new instances of said class?
Passing a class into a React component so that it can create new instances of said class?

Time:10-27

I have a component which renders a data structure. I am trying to create an editor for that structure and want to use the same renderer, but with certain sub-components overridden. The renderer has some data that I'd like to pass into the sub-component so I thought it might be best to use a passed class which the renderer would be able to call and include the data as props. Something roughly like:

class Editor extends React.Component{
    render(){
        return <Renderer overrideClass={OverridenComponent}/>;
    }
}
class Renderer extends React.Component{
    render(){
        return <this.props.overrideClass importantData="TEST"/>;
    }
}
class OverriddenComponent extends React.Component{
    render(){
        return <div>{this.props.importantData}</div>;
    }
}

I would expect that creating an <Editor/> would result in <div>TEST</div> in the DOM, but instead I am getting what is equivilant to <overridencomponent></overridencomponent>, specifically non-capitalized and with no content.

Is this sort of behavior supported in some way? Is there a better way to accomplish this sort of overridable content while still allowing the Renderer class to pass data to the overridden version?

CodePudding user response:

JSX only renders components which names are Capitalized. Therefore you should save the override class into a variable that is Capitalized.

Try:

class Editor extends React.Component{
    render(){
        return <Renderer overrideClass={OverridenComponent}/>;
    }
}
class Renderer extends React.Component{
    render(){
        const Component = this.props.overrideClass
        return <Component importantData="TEST"/>;
    }
}
class OverriddenComponent extends React.Component{
    render(){
        return <div>{this.props.importantData}</div>;
    }
}

CodePudding user response:

In addition to the marked answer above, I found that passing in a callback function which takes the props and returns the class instance to be effective as well. It looked like:

class Editor extends React.Component{
    render(){
        return <Renderer overrideClass={(importantData) =>
            <OverridenComponent importantData={importantData}/>}
        />;
    }
}
class Renderer extends React.Component{
    render(){
        return this.props.overrideClass("TEST");
    }
}
class OverriddenComponent extends React.Component{
    render(){
        return <div>{this.props.importantData}</div>;
    }
}

I'm not sure exactly which method is better, but his answer was closer to what I was actually asking for as far as passing a class. I suspect that his way is more flexible too.

  • Related