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:
On another case, for trip search result, I may have a header component like this:
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?
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.
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.
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.
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>
);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With