Elliott Stone
Elliott Stone

Reputation: 11

How can I pass a component as a prop into another component in React?

I am new to React and I have a Java background, so forgive if the wording of this question doesn't really make sense.

I would like to "pass" an instance of a component into another component (that uses the passed component in it's render() method)

How can I do this?

Upvotes: 1

Views: 85

Answers (2)

Shubhaw Kumar
Shubhaw Kumar

Reputation: 721

The question is not very clear. But from what I understand, there can be multiple ways of doing this.

Component 1

class Component1 extends React.Component {
    render() {
        return <h1>Component 1</h1>;
    }
}

Component 2

class Component2 extends React.Component {
    render() {
        return (
            <React.Fragment>
                <h1>Component 2</h1>
                {children}
            </React.Fragment>
    }
}

MainComponent

class MainComponent extends React.Component {
    render() {
        return (
            <Component2>
                <Component1 />
            </Component2>
    }
}

Here, one 'instance' of Component1 is passed to Component2 which then renders the Component1 as one of its children.

Another way is to use Render Props. To understand Render Props in a better way, you can watch this Youtube tutorial.

Upvotes: 0

bumbaneitr11
bumbaneitr11

Reputation: 101

Sorry for the bad naming, but I hope you're able to see the different use cases from what I understand from your question:

// Component that receives another component being passed in its props
function Renderer1(props) {
  return props.component
}

// Component that receives another component and creates an instance of it
// this way this component has more control of rendering the passed component
// and the props you want to pass to it
function Renderer2(props) {
  return <props.component />
}

// Component being passed in props
function PropComponent(){
   return <div>Hello world!</div>
}

// Rendered component, example 1
function Main1() { 
   return <Renderer1 component={() => <PropComponent />} />
}

// Rendered component, example 2, this one uses Renderer2 component
function Main2() { 
   return <Renderer2 component={PropComponent} />
}

I hope with these different examples you can get an idea of how to continue with what you're working on :)

Upvotes: 2

Related Questions