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

Edaurd B

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?

Ali Faris

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

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related