Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing component as a prop in react native

Tags:

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?

like image 394
Sakibur Rahman Avatar asked Jun 27 '18 06:06

Sakibur Rahman


People also ask

Can I pass component as a prop?

In the previous example, it was only a string variable. But props can be any JavaScript data type from integers over objects to arrays. Via props you can even pass React components as well, which you will learn about later.

How do you pass an object as a prop in React?

Use the spread syntax (...) to pass an object as props to a React component, e.g. <Person {... obj} /> . The spread syntax will unpack all of the properties of the object and pass them as props to the specified component.

How do I pass JSX as props?

You want to use JSX inside your props You can simply use {} to cause JSX to parse the parameter. The only limitation is the same as for every JSX element: It must return only one root element.


1 Answers

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>
        );
    }
}
like image 54
Paolo Dell'Aguzzo Avatar answered Oct 21 '22 13:10

Paolo Dell'Aguzzo