10

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?

1 Answer 1

28

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>
        );
    }
}
Sign up to request clarification or add additional context in comments.

4 Comments

Works perfectly fine, thanks, it was so simple even to think around.
Can you please tell me how to send send the componet as the prop as my app is showing Functions are not valid as a React child. This may happen if you return a Component instead of <Component /> from render. Or maybe you meant to call this function rather than return it.
@SayokMajumder when you do like the answer say to do ( use the prop within a {} like {this.props.header}), and your component is a function, you must provide the header as <MyComponent header={<Header />} {...} />. You are probably missing < and /> around the Headercomponent.
What if , if we want to pass some thing to {this.props.chindren} ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.