Edaurd B
Edaurd B

Reputation: 183

How to pass props to a component passed as props in React?

I want to pass props to a component that is passed as props like this:

<Field
      name="persons"
      component={Persons} 
/>

I've tried this but it didn't work:

component={<Person prop={prop} />}

How can I make this work?

Upvotes: 7

Views: 7904

Answers (2)

Ali Faris
Ali Faris

Reputation: 18630

you can pass the component type and props in two different properties

<Foo component={Bar} componentProps={...} />

then in Foo component, you do this

 render() {
    const Component = this.props.component;
    const props = this.props.componentProps;
    return <div> ... <Component {...props}/> ...</div>
 }

or you can pass a function that renders you component like this

<Foo component={() => <Bar props />}/>

then in Foo component, you do this

 render() {
    return <div> ... {this.props.component()} ...</div>
 }

or you can do as you suggested in the question like this

<Foo component={<Bar props/>}/>

then in Foo component, you do this

 render() {
    return <div> ... {this.props.component} ...</div>
 }

its all depend on how you will use the passed component in Foo component, or in your case the Field component

Upvotes: 13

buzatto
buzatto

Reputation: 10382

a component is nothing more than a function that returns a react component. when you do <Person prop={prop} /> you are actually invoking that function in jsx style.

Therefore, you need to wrap your Person component into another function that returns Person like:

// props here is in case <Field> pass some props to component
component={(props) => <Person {...props} prop={prop} />}

Upvotes: 2

Related Questions