Home > database >  How to make reusable components in Jetpack compose?
How to make reusable components in Jetpack compose?

Time:11-09

I'm trying to create a TextField reusable component so I did this

@Composable
fun TextFieldComponent(state: Any, placeholder: String) {
    TextField(
        value = state,
        onValueChange = { textFieldValue -> state = textFieldValue },
        placeholder = { Text(placeholder, color = MaterialTheme.colors.secondary) }
    )
}

but I'm getting these errors

enter image description here

and that's how I'm calling the component

val textFieldState by rememberSaveable { mutableStateOf("") }
TextFieldComponent(state = textFieldState, placeholder = "Email")

so is there any fix?

CodePudding user response:

Just turn state into a MutableState<String>, so you can modify it from inside the function:

@Composable
fun TextFieldComponent(state: MutableState<String>, placeholder: String) {
    TextField(
        value = state.value,
        onValueChange = { textFieldValue -> state.value = textFieldValue },
        placeholder = { Text(placeholder, color = MaterialTheme.colors.secondary) }
    )
}

However, it is usually preferable to instead provide a value and a change listener to the composable function:

@Composable
fun TextFieldComponent2(value: String, onValueChange: (String) -> Unit, placeholder: String) {
    TextField(
        value = value,
        onValueChange = { textFieldValue -> onValueChange(textFieldValue) },
        placeholder = { Text(placeholder, color = MaterialTheme.colors.secondary) }
    )
}

Such solution is more flexible as the caller could very easily provide any behavior on the value change (thanks @Jakoss)

  • Related