s-leg3ndz
s-leg3ndz

Reputation: 3518

React Native components name with point parameter

Is it possible to create custom component in React Native with parameters, ex. : transform <PageHeader /> to <Page.Header /> or <PageContent /> to <Page.Content />.

I've see this syntaxe with Picker component in React Native.

<Picker
  selectedValue={this.state.lang}
  onValueChange={(itemValue, itemIndex) => this.switchLang(itemValue)}
  style={Styles.picker}
>
  <Picker.Item label="EN" value="en-EN" />
  <Picker.Item label="FR" value="fr-FR" />
</Picker>

Thank you community :)

Upvotes: 4

Views: 89

Answers (2)

Shubham Khatri
Shubham Khatri

Reputation: 281656

You would write your components exposing the other components as static class variables which you can access from the class Instance for example you define your components like

class PageContent extends React.Component {}

class PageHeader extends React.Component {}

and then declare your page component like

class Page extends React.Component {
   static Content = PageContent;
   static Header = PageHeader;

}

export default Page

Now if your import Page , you could access Header and Content like <Page.Content/> and <Page.Header/>

Now if the Page component doesn't do any React stuff, you could instead write it a basic class

Upvotes: 2

Val
Val

Reputation: 22797

I used to do it this way:

Pager.js

import React, { Component } from 'react';

export class Pager extends Component {
    ...
}

Pager.Header = class extends Component {
    ...
}

Then you can use it in your app. For VSCode it will also show auto complete Header after Pager..

app.js

import { Pager } from './Pager';

<Pager>
    <Pager.Header />
</Pager>

Upvotes: 1

Related Questions