Home > database >  How to assign the value of a textfield to a hoistedState in compose?
How to assign the value of a textfield to a hoistedState in compose?

Time:11-22

I want to make a reusable component including between other things a TextField, like

@Composable
fun ReusableFormField(textFieldValue: TextFieldValue){
   --label stuff here--
   TextField(value = textFieldValue, onValueChange = {
            textFieldValue = it)
   })
   --helper stuff here
}

But I can't find a way to assign the textFieldValue to a wrapping component as you cannot pass a variable by reference with something like ref or out in the parameters.

CodePudding user response:

You need to provide a lambda parameter to ReusableFormField to update the value.

@Composable
fun ReusableFormField(
    value: TextFieldValue,
    onValueChange: (TextFieldValue) -> Unit
){
   // --label stuff here--
   TextField(value = value, onValueChange = onValueChange)
   // --helper stuff here
}

CodePudding user response:

If you remembered textFieldValue state above you can pass event top and modify state there. then it will be recomposed.

@Composable
fun ParentComposable(){
    var textFieldValue by remember {
        mutableStateOf(TextFieldValue(""))
    }
    ReusableFormField(
        textFieldValue,
    ){
        textFieldValue = it
    }
}

@Composable
fun ReusableFormField(
    textFieldValue: TextFieldValue,
    onValueChange: (TextFieldValue) -> Unit
){
    TextField(value = textFieldValue, onValueChange = {
        textFieldValue = it)
    })
}
  • Related