Sakibur Rahman
Sakibur Rahman

Reputation: 904

Passing component as a prop in react native

In order to make a customize-able component, what should I do to pass component as a prop in another component.

I have a header component which may be customized depending on current pages actions.

For example, for autocomplete search, I may have a header component like this:

enter image description here

On another case, for trip search result, I may have a header component like this: enter image description here

I want build to a component that will receive a component as a prop and will render it to the current component. What is the best way to do this in react-native way?

Upvotes: 9

Views: 17550

Answers (1)

Paolo Dell'Aguzzo
Paolo Dell'Aguzzo

Reputation: 1431

You can pass a component as a prop or as child. The first way is this one:

export default class Home extends Component{
    render(){
        return(
            <View>
                <PageComponent header = {<Header title = {".."}/>}/>
            </View>
        );
    }
}

export default class PageComponent extends Component{
    render(){
        return(
            <View>
                {this.props.header}
                <View>
                    ...
                </View>
            </View>
        );
    }
}

The second way is:

export default class Home extends Component{
    render(){
        return(
            <View>
                <PageComponent>
                    <Header title = {".."}/>
                </PageComponent>
            </View>
        );
    }
}
export default class PageComponent extends Component{
    render(){
        return(
            <View>
                {this.props.children}
                <View>
                    ...
                </View>
            </View>
        );
    }
}

Upvotes: 28

Related Questions