Hanif Nr
Hanif Nr

Reputation: 462

React - Pass component as argument to another component

I want to have header that can custom view based on which screen its called. So i need to pass component as argument to my header component. But it seems doesn't work.

Here's my custom component

...    
const ComponentRight = () => {
      return (
        <Right>
            <Button transparent onPress= {() => {
                {enablePinned ?
                  addChatPinned(chatSelected) :
                  removeChatPinned(chatSelected)
                }
            }}>
              {enablePinned ?
                <Icon type= 'MaterialCommunityIcons' name= 'pin'/> :
                <Icon type= 'MaterialCommunityIcons' name= 'pin-off'/>
              }
            </Button>
            <Button 
              transparent
              onPress= {() => deleteChatList(chatSelected)}>
              <Icon type= 'FontAwesome5' name= 'trash' style= {{fontSize: 20}}/>
            </Button>
            <Button transparent>
              <Icon type= 'MaterialIcons' name= 'archive' style= {{fontSize: 25}}/>
            </Button>
          </Right>
      )
    }

    return (
      <Container>
        {showAction ?
          <SelectHeader
            onBack= {resetChatSelected()}
            itemCount= {chatSelected.length}
            componentRight= {ComponentRight}/> // passing my component as argument
...

And this my header component

const SelectHeader = ({onBack, itemCount, componentRight}) => {
    return (
        <Header style= {appStyles.headerBackgroundColor}>
            <Left style= {{flexDirection: 'row'}}>
              <Button 
                transparent 
                style= {{marginRight: 30}}
                onPress= {() => {onBack}}>
                <Icon type='Ionicons' name= 'md-arrow-back' style= {{fontSize: 25}} color= 'white'/>
              </Button>
              <Title style= {appStyles.appTitle, {alignSelf: 'center'}}>{itemCount}</Title>
            </Left>
            <Body/>
            {componentRight}
          </Header> 
    )
}

export default SelectHeader

Anyone know how to accomplish this? thanks

Upvotes: 2

Views: 4419

Answers (2)

thuva4
thuva4

Reputation: 1225

This is called Higher-order components[1], Just pass the component as props and use it inside the render method.

  1. https://reactjs.org/docs/higher-order-components.html

Upvotes: 1

Lu&#239;s
Lu&#239;s

Reputation: 2833

You can pass a component like this:

<MyComponent
  propComponent={<MyPropComponent />}
/>

You can even pass down props to that component if necessary.

Upvotes: 1

Related Questions