TIMEX
TIMEX

Reputation: 272374

How can I pass a component as a prop in React Native?

In my AutoSuggest Component (which renders FlatList), I would like to render different types of cells.

I'd like to pass different Components into AutoSuggest, such as:

<Suggest
    customCell={<SimpleUserCell/>} //or any type of cell
/>

Inside Suggest.js, my render will look like this:

render(){
    <FlatList 
        renderItem={(props) => {
            return(
               <this.props.customCell extraData={this.suggestData}/>
            )
        }}
     />
}

How can I achieve this?

Upvotes: 1

Views: 1032

Answers (1)

Chris
Chris

Reputation: 470

To pass a component as a prop in React Native you can do the following, can be seen at: https://codesandbox.io/s/6v24n3q92z Hopefully this helps. You will need to extrapolate to get your specific use case working.

class ComponentOne extends React.Component {
  render() {
    return (
      <div>
        I am Component One see my array
        <ul>{this.props.extraData.map(number => <li>number {number}</li>)}</ul>
      </div>
    );
  }
}

class Suggest extends React.Component {
  render() {
    var anArray = [1, 2, 3, 4, 5];
    var CustomComponent = this.props.customCell;
    return <CustomComponent extraData={anArray} />;
  }
}

function App() {
  return <Suggest customCell={ComponentOne} />;
}

Upvotes: 2

Related Questions