Merig
Merig

Reputation: 2011

Jetpack Compose props typing

I'm looking for an elegant way to type Composable functions parameters. I'm used to React, where you pass a single props parameter without having to have a million of them.

For reference, what is the cleanest way to to something like this

interface MyCompProps {
   foo: string
   bar: number
} 

function MyComp(props: MyCompProps) {...}

with Compose?

Do I have to create a class and instantiate one when I build the props? Do I use maps? Is it the wrong way of thinking about it?

Right now I'm doing something like

class ProjectListItemProps(
    val imageUrl: String,
    val projectName: String,
    val createdAt: String
)

@Composable
fun ProjectListItem(props: ProjectListItemProps) {...}

Upvotes: 2

Views: 985

Answers (2)

ameencarpenter
ameencarpenter

Reputation: 2599

Yes. In Android it's recommended to create data classes to represent data objects as entities.

For example, in a notes app you would create a note data class as following:

data class Note(
    var id: String = "",
    var dateAdded: Long = 0,
    var title: String = "",
    var textContent: String = "",
    var isFavorite: Boolean = false,
)

Then in compose you can create a composeable that represents the note in the UI:

@Composable
fun Note(note: Note){
    //child composables
}

But if the parameters don't represent an entity, such as whether to show ProgressBar or not, you shouldn't put it in a class.

And remember, in Kotlin you can use default parameters, then when you call the function you pass a parameter only when you want to pass a value different from the default one.

Example:

@Composable
fun Page(showProgressBar: Boolean = false){
    //child composables
}

If you called Page without passing any parameters it won't show the progress bar, because showProgressBar = true by default. But if want to show it you pass true to override the default value:

Note() /*progress bar is hidden.*/
Note(showProgressBar = true) /*progress bar is shown*/

Upvotes: 2

Róbert Nagy
Róbert Nagy

Reputation: 7680

I think it's a good idea to check out the design of the Composables provided by the framework. For example:

LazyColumn(
    contentPadding = PaddingValues(horizontal = 16.dp, vertical = 8.dp),
) {
    // ...
}

So in short, yes it is a good idea, and I'd use it for grouping attributes.

Upvotes: 1

Related Questions